boost(barrier)

时间:2023-03-09 07:31:58
boost(barrier)

barrier:栅栏的意思,当barrier bar(3),这三个线程会放到栅栏中,等第三个线程执行时一起唤醒,然后返回

barrier
barrier类的接口定义如下:
class barrier : private boost::noncopyable // Exposition only
{
public:
// construct/copy/destruct
barrier(size_t n);
~barrier(); // waiting
bool wait();
}; barrier类为我们提供了这样一种控制线程同步的机制:
前n - 1次调用wait函数将被阻塞,直到第n次调用wait函数,而此后第n + 1次到第2n - 1次调用wait也会被阻塞,直到第2n次调用,依次类推。
barrier::wait的实现十分简单: barrier::barrier(unsigned int count)
: m_threshold(count), m_count(count), m_generation()
{
if (count == )
throw std::invalid_argument("count cannot be zero.");
} bool barrier::wait()
{
boost::mutex::scoped_lock lock(m_mutex); // m_mutex is the base of barrier and is initilized by it's default constructor.
unsigned int gen = m_generation; // m_generation will be 0 for call 1~n-1, and 1 for n~2n - 1, and so on if (--m_count == )
{
m_generation++; // cause m_generation to be changed in call n/2n/
m_count = m_threshold; // reset count
m_cond.notify_all(); // wake up all thread waiting here
return true;
} while (gen == m_generation) // if m_generation is not changed, lock current thread.
m_cond.wait(lock);
return false;
} 因此,说白了也不过是mutex的一个简单应用。
以下是一个使用barrier的例子: #include <boost/thread/thread.hpp>
#include <boost/thread/barrier.hpp> int i = ;
boost::barrier barr(); // call barr.wait 3 * n times will release all threads in waiting void thread()
{
++i;
barr.wait();
} int main()
{
boost::thread thrd1(&thread);
boost::thread thrd2(&thread);
boost::thread thrd3(&thread); thrd1.join();
thrd2.join();
thrd3.join(); return ;
} 如果去掉其中thrd3相关的代码,将使得线程1、2一直处于wait状态,进而使得主线程无法退出。

就实现了等到线程执行完时一起返回,有个小疑问,main中创建三个线程,然后都访问了i,这样岂不是错了?毕竟互斥的操作是在wait里面的。