如何使用增强屏障

rah*_*man 14 c++ boost

什么是提升:障碍,如何使用这种提升方法.你能给我一个明确的例子,因为我发现了以下例子:

    bool wait()
    {
        boost::mutex::scoped_lock lock(m_mutex);
        unsigned int gen = m_generation;

        if (--m_count == 0)
        {
            m_generation++;
            m_count = m_threshold;
            m_cond.notify_all();
            return true;
        }

        while (gen == m_generation)
            m_cond.wait(lock);
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中:m_cond.notify_all();是否进入其他等待线程?你能告诉我有关屏障功能的信息吗?谢谢.

For*_*veR 15

notify_all,通知等待线程.

障碍是一个简单的概念.也称为集合点,它是多个线程之间的同步点.屏障被配置用于特定数量的线程(n),并且当线程到达屏障时,它们必须等待直到所有n个线程都到达.一旦第n个线程到达屏障,所有等待的线程就可以继续,并且屏障被重置.

简单的例子.只有当3个线程在屏障上调用wait函数时,才会输出当前值.

#include <boost/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/bind.hpp>
#include <boost/atomic.hpp>

boost::mutex io_mutex;

void thread_fun(boost::barrier& cur_barier, boost::atomic<int>& current)
{
    ++current;
    cur_barier.wait();
    boost::lock_guard<boost::mutex> locker(io_mutex);
    std::cout << current << std::endl;
}

int main()
{
    boost::barrier bar(3);
    boost::atomic<int> current(0);
    boost::thread thr1(boost::bind(&thread_fun, boost::ref(bar), boost::ref(current)));
    boost::thread thr2(boost::bind(&thread_fun, boost::ref(bar), boost::ref(current)));
    boost::thread thr3(boost::bind(&thread_fun, boost::ref(bar), boost::ref(current)));
    thr1.join();
    thr2.join();
    thr3.join();
}
Run Code Online (Sandbox Code Playgroud)