我有一個unordered_map的unordered_map,它存儲了一個對象的指針。無序的地圖由多個線程共享。我需要迭代每個對象並執行一些耗時的操作(如通過網絡發送等)。我怎麼能鎖定多個unordered_map,以便它不會阻塞太久?對鎖內的STL容器執行耗時的操作
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)
如果某些map2項目在解鎖後被抹去會發生什麼? – 9dan 2011-01-11 08:11:30