【问题标题】:Can 'mutex' of boost be used to for mutual exclusion among more than two threads?boost的'mutex'可以用于两个以上线程之间的互斥吗?
【发布时间】:2015-07-29 10:55:18
【问题描述】:
以下是 Boost 中两个线程之间互斥的示例:
mutex m;
thread1:
m.lock();
... /* A */
m.unlock();
thread2:
m.lock();
... /* B */
m.unlock();
我的问题是上面的代码是否可以用来解决两个以上线程之间的冲突?在我看来,它只提供了两个线程之间的互斥。
如果上述方法不起作用,如何实现两个以上线程之间的互斥?
【问题讨论】:
标签:
c++
multithreading
boost
mutex
【解决方案1】:
是的,您可以在任意多个线程中使用它。
不过,我建议使用std::mutex 和std::lock_guard:
std::mutex m;
//thread1:
{
std::lock_guard<std::mutex> lg(m); //<-- Automatically locks m upon construction of lg
//... /* A */
} //<- automatically unlocks m at the end of lg's life time
//thread2:
{
std::lock_guard<std::mutex> lg(m);
//... /* B */
}
//thread3:
{
std::lock_guard<std::mutex> lg(m);
//... /* C */
}