I ask a question about multithreading.
Say I have two global vectors,
std::vector<MyClass1*> vec1
and
std::vector<MyClass2*> vec2.
In addition, I have a total of 4 threads that have access to vec1 and vec2 . Can I write code as follows?
void thread_func() // this is the function that will be executed by a thread { MyClass1* myObj1 = someFunction1(); MyClass2* myObj2 = someFunction2(); // I want to push back vec1, then push back vec2 in an atomic way pthread_mutex_lock(mutex); vec1.push_back(myObj1); vec2.push_back(myObj2); pthread_mutex_unlock(mutex); } for(int i=0; i<4; i++) { pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); }
What I want to do is that I want to push_back on vec1 and then push_back on vec2 .
I'm a newbie, and I feel that only one variable can be locked with a mutex. In other words, you can only set vec1.push_back (myObj1) or vec2.push_back (myObj2) between pthread_mutex_lock (mutex) and pthread_mutex_unlock (mutex) .
I don't know if my code is correct or not. Can someone fix me if I'm wrong?
Shawn source share