【发布时间】:2012-07-08 12:46:56
【问题描述】:
在我的多线程应用程序中使用std:map 时遇到问题。当线程写入该对象时,我需要锁定地图对象。并行读取此对象的另一个线程应该存储直到写入过程完成。
示例代码:
std::map<int, int> ClientTable;
int write_function() //<-- only one thread uses this function
{
while(true)
{
//lock ClientTable
ClientTable.insert(std::pair<int, int>(1, 2)); // random values
//unlock ClientTable
//thread sleeps for 2 secs
}
}
int read_function() //<--- many thread uses this function
{
while(true)
{
int test = ClientTable[2]; // just for test
}
}
如何锁定这个 std::map 对象并正确同步这个线程?
【问题讨论】:
-
您可能希望将
read_function更改为使用map的find成员函数而不是operator[],因为后者实际上可以修改map。通常这是一种轻微的烦恼(在最坏的情况下),但在这种情况下,会变得更加严重。
标签: c++ multithreading synchronization