Is it possible to block several variables at the same time?

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?

+5
source share
2 answers

Your code is correct. A mutex is something that is locked, not a variable (s). You block the mutex to protect part of the code from being executed by multiple threads, most often it is data protection, but in general it really protects a section of code.

+5
source

Yes, you can write this way, but there are several methods that you should definitely consider:

  • Fixed lock pattern for exception safety and better overall reliability. This is well explained in this answer.
  • Avoid the global ones so that the optimizer works smarter for you. Try to combine the data into logical classes and implement a lock inside it. Fewer variables also give you better extensibility.
0
source

All Articles