我的多线程应用程序中使用std:map
时出现问题。当线程写入此对象时,我需要锁定地图对象。同时读取该对象的另一个线程应该购物,直到写入过程完成。锁定std :: map C++
示例代码:
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 ::地图对象和正确同步此线程?
你可能想改变'read_function'使用'map'的'find'成员函数,而不是'运营商[]',因为后者实际上可以修改'地图'。通常这是一个温和的烦恼(最坏的情况),但在这种情况下,变得更加严重。 – 2012-07-08 14:06:32