加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何使用增压屏障

发布时间:2020-12-16 05:45:07 所属栏目:百科 来源:网络整理
导读:什么是boost:barrier,如何使用这种boost方法.可以给我一个明确的例子,因为我发现了以下几个例子: bool wait() { boost::mutex::scoped_lock lock(m_mutex); unsigned int gen = m_generation; if (--m_count == 0) { m_generation++; m_count = m_threshol
什么是boost:barrier,如何使用这种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;
    }

在上面的代码中:m_cond.notify_all();是进入其他等待线程吗?
你能否明确说明屏障功能?谢谢.

解决方法

notify_all,通知等待线程.

A barrier is a simple concept. Also known as a rendezvous,it is a
synchronization point between multiple threads. The barrier is
configured for a particular number of threads (n),and as threads
reach the barrier they must wait until all n threads have arrived.
Once the n-th thread has reached the barrier,all the waiting threads
can proceed,and the barrier is reset.

简单的例子.只有当3个线程在屏障上调用等待功能时,才会输出当前值.

#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(current)));
    boost::thread thr3(boost::bind(&thread_fun,boost::ref(current)));
    thr1.join();
    thr2.join();
    thr3.join();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读