天天看點

Boost Thread學習筆記四

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 }

 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

Boost Thread學習筆記四

12 

13     if (--m_count == 0)

14     {

15         m_generation++;    // cause m_generation to be changed in call n/2n/

Boost Thread學習筆記四

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 }

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;

如果去掉其中thrd3相關的代碼,将使得線程1、2一直處于wait狀态,進而使得主線程無法退出。

xtime

xtime是boost::thread中用來表示時間的一個輔助類,它是一個僅包含兩個成員變量的結構體:

1 struct xtime

2 {

3 //

Boost Thread學習筆記四

4     xtime_sec_t sec;

5     xtime_nsec_t nsec;

6 };

condition::timed_wait、thread::sleep等涉及逾時的函數需要用到xtime。

需要注意的是,xtime表示的不是一個時間間隔,而是一個時間點,是以使用起來很不友善。為了友善使用xtime,boost提供了一些輔助的xtime操作函數,如xtime_get、xtime_cmp等。

以下是一個使用xtime來執行sleep的例子(跟簡單的一句Sleep比起來,實在是太複雜了),其中用到了xtime初始化函數xtime_get:

 2 #include <boost/thread/xtime.hpp>

 3 #include <iostream>

 4 

 5 int main()

 6 {

 7     boost::xtime xt;

 8     boost::xtime_get(&xt, boost::TIME_UTC);    // initialize xt with current time

 9     xt.sec += 1;    // change xt to next second

10     boost::thread::sleep(xt);    // do sleep

11 

12     std::cout << "1 second sleep over." << std::endl;

13 

14     return 0;

15 } 

繼續閱讀