barrier:栅栏的意思,当barrier bar(3),这三个线程会放到栅栏中,等第三个线程执行时一起唤醒,然后返回
barrier barrier类的接口定义如下: 1 class barrier : private boost::noncopyable // Exposition only 2 { 3 public: 4 // construct/copy/destruct 5 barrier(size_t n); 6 ~barrier(); 7 8 // waiting 9 bool wait(); 10 }; barrier类为我们提供了这样一种控制线程同步的机制: 前n - 1次调用wait函数将被阻塞,直到第n次调用wait函数,而此后第n + 1次到第2n - 1次调用wait也会被阻塞,直到第2n次调用,依次类推。 barrier::wait的实现十分简单: 1 barrier::barrier(unsigned int count) 2 : m_threshold(count), m_count(count), m_generation(0) 3 { 4 if (count == 0) 5 throw std::invalid_argument("count cannot be zero."); 6 } 7 8 bool barrier::wait() 9 { 10 boost::mutex::scoped_lock lock(m_mutex); // m_mutex is the base of barrier and is initilized by it's default constructor. 11 unsigned int gen = m_generation; // m_generation will be 0 for call 1~n-1, and 1 for n~2n - 1, and so on 12 13 if (--m_count == 0) 14 { 15 m_generation++; // cause m_generation to be changed in call n/2n/ 16 m_count = m_threshold; // reset count 17 m_cond.notify_all(); // wake up all thread waiting here 18 return true; 19 } 20 21 while (gen == m_generation) // if m_generation is not changed, lock current thread. 22 m_cond.wait(lock); 23 return false; 24 } 因此,说白了也不过是mutex的一个简单应用。 以下是一个使用barrier的例子: 1 #include <boost/thread/thread.hpp> 2 #include <boost/thread/barrier.hpp> 3 4 int i = 0; 5 boost::barrier barr(3); // call barr.wait 3 * n times will release all threads in waiting 6 7 void thread() 8 { 9 ++i; 10 barr.wait(); 11 } 12 13 int main() 14 { 15 boost::thread thrd1(&thread); 16 boost::thread thrd2(&thread); 17 boost::thread thrd3(&thread); 18 19 thrd1.join(); 20 thrd2.join(); 21 thrd3.join(); 22 23 return 0; 24 } 如果去掉其中thrd3相关的代码,将使得线程1、2一直处于wait状态,进而使得主线程无法退出。
就实现了等到线程执行完时一起返回,有个小疑问,main中创建三个线程,然后都访问了i,这样岂不是错了?毕竟互斥的操作是在wait里面的。