我有一个存储对象指针的 unordered_map 的 unordered_map。无序映射由多个线程共享。我需要遍历每个对象并执行一些耗时的操作(比如通过网络发送它等)。我如何锁定多个 unordered_map 以使其不会阻塞太久?
typedef std::unordered_map<string, classA*>MAP1;
typedef std::unordered_map<int, MAP1*>MAP2;
MAP2 map2;
pthread_mutex_lock(&mutexA) //how could I lock the maps? Could I reduce the lock granularity?
for(MAP2::iterator it2 = map2.begin; it2 != map2.end; it2++)
{
for(MAP1::iterator it1 = *(it2->second).begin(); it1 != *(it2->second).end(); it1++)
{
//perform some time consuming operation on it1->second eg
sendToNetwork(*(it1->second));
}
}
pthread_mutex_unlock(&mutexA)
最佳答案
您可以将所有这些对象存储在一些其他结构(如列表)中并对其进行迭代,这样您就不必锁定映射。
您还可以尝试创建数据的拷贝并处理拷贝 - 这样您的 map 就可以在处理拷贝的同时进行修改。
关于c++ - 在锁内对 STL 容器执行耗时操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4654522/