Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I lock multiple variables simultaneously?

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?

like image 827
Shawn Avatar asked May 17 '15 16:05

Shawn


Video Answer


1 Answers

Your code is correct. The mutex is the thing being locked, not the variable(s). You lock the mutex to protect a piece of code from being executed by more than one thread, most commonly this is to protect data but in general it's really guarding a section of code.

like image 61
Ron Kuper Avatar answered Sep 29 '22 18:09

Ron Kuper