【问题标题】: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::mutexstd::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 */
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多