Performing time consuming operation on STL container within a lock

Posted by Ashley on Stack Overflow See other posts from Stack Overflow or by Ashley
Published on 2011-01-11T05:30:17Z Indexed on 2011/01/11 5:53 UTC
Read the original article Hit count: 200

Filed under:
|

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)

© Stack Overflow or respective owner

Related posts about c++

Related posts about multithreading