gpt4 book ai didi

c++ - 如何使用 boost 屏障

转载 作者:IT老高 更新时间:2023-10-28 22:59:46 37 4
gpt4 key购买 nike

什么是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个线程在barrier上调用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();
}

关于c++ - 如何使用 boost 屏障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11407577/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com