Multithreading with STL container

Posted by Steven on Stack Overflow See other posts from Stack Overflow or by Steven
Published on 2011-01-11T04:23:43Z Indexed on 2011/01/11 9:53 UTC
Read the original article Hit count: 191

Filed under:
|
|

I have an unordered map which stores a pointer of objects. I am not sure whether I am doing the correct thing to maintain the thread safety.

typedef std::unordered_map<string, classA*>MAP1;
MAP1 map1;
pthread_mutex_lock(&mutexA)
   if(map1.find(id) != map1.end())
   {
      pthread_mutex_unlock(&mutexA); //already exist, not adding items   
   }
   else
   {
       classA* obj1 = new classA;
       map1[id] = obj1;
       obj1->obtainMutex(); //Should I create a mutex for each object so that I could obtain mutex when I am going to update fields for obj1?
       pthread_mutex_unlock(&mutexA); //release mutex for unordered_map so that other threads could access other object
       obj1->field1 = 1;
       performOperation(obj1); //takes some time
       obj1->releaseMutex(); //release mutex after updating obj1
   }

© Stack Overflow or respective owner

Related posts about c++

Related posts about multithreading