简体   繁体   English

我可以同时锁定多个变量吗?

[英]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 . 另外,我总共有4个线程可以访问vec1vec2 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 . 我想要做的是,我想在vec1上执行push_back,然后在vec2上执行push_back。

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) . 换句话说,只能在pthread_mutex_lock(mutex)pthread_mutex_unlock(mutex)之间放置vec1.push_back(myObj1)vec2.push_back(myObj2

I don't know if my code above is correct or not. 我不知道上面的代码是否正确。 Can someone correct me if I'm wrong? 如果我错了,有人可以纠正我吗?

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. 您锁定互斥锁以保护一段代码不被多个线程执行,最常见的是保护数据,但一般来说它实际上是在保护一段代码。

Yes, you can write like this but there are a few techniques you should definitely consider: 是的,你可以像这样写,但你应该考虑一些技巧:

  1. Scoped lock pattern for exception-safety and better robustness in general. Scoped锁定模式可实现异常安全性和更好的稳健性。 This is nicely explained in this answer 这个答案中很好地解释了这一点
  2. Avoid globals to let optimizer work smarter for you. 避免全局变量让优化器更智能地为您工作。 Try to group data into logical classes and implement locking inside it's methods. 尝试将数据分组到逻辑类中并在其内部实现锁定。 Smaller scope of variables also gives you better extensibility. 较小的变量范围也为您提供了更好的可扩展性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM