Performing time consuming operation on STL container within a lock
- by Ashley
I have an unordered_map of an unordered_map which stores a pointer of objects. The unordered map is being shared by multiple threads. I need to iterate through each object and perform some time consuming operation (like sending it through network etc) . How could I lock the multiple unordered_map so that it won't blocked for too long?
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)