I'm asking 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 number of 4 threads which 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 perform push_back on vec1 followed by push_back on vec2.
I'm a newbie and I have a feeling that one can only lock on one variable with a mutex. In other words, one can only put either vec1.push_back(myObj1) or vec2.push_back(myObj2) in between pthread_mutex_lock(mutex) and pthread_mutex_unlock(mutex).
I don't know if my code above is correct or not. Can someone correct me if I'm wrong?