#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/xtime.hpp>
#include <iostream>
#include <time.h> // for time()
#include <Windows.h> // for Sleep, change it for other platform, we can use
// boost::thread::sleep, but it's too inconvenient.
#include <boost/thread/barrier.hpp>
int i = 0;
// barrier类为我们提供了这样一种控制线程同步的机制:
// 前n - 1次调用wait函数将被阻塞,直到第n次调用wait函数,
// 而此后第n + 1次到第2n - 1次调用wait也会被阻塞,直到第2n次调用,依次类推。
//
// call barr.wait 3 * n times will release all threads in waiting
// example 表示 n = 3 , 前两个线程会被阻塞, 到三个线程可以结束;
// 当n 改为 2 或者 4 的时候,多线程都不会停止
boost::barrier barr(3);
boost::mutex myMutex;
void thread()
{
{
boost::mutex::scoped_lock lock(myMutex);
++i;
std::cout<<" i = "<<i<<std::endl;
std::cout<<"this_thread::get_id() "<<std::dec<<boost::this_thread::get_id()<<std::endl;
}
barr.wait();
}
void main ()
{
boost::thread thrd1(&thread);
std::cout<<"thrd1 :"<<thrd1.get_id()<<std::endl;
boost::thread thrd2(&thread);
std::cout<<"thrd2 : "<<thrd2.get_id()<<std::endl;
boost::thread thrd3(&thread);
std::cout<<"thrd3 : "<<thrd3.get_id()<<std::endl;
thrd1.join();
thrd2.join();
thrd3.join();
system("pause");
}
output
thrd1 :006980A8
i = 1
thrd2 : 006980D8
this_thread::get_id() 006980A8
thrd3 : 00698108
i = 2
this_thread::get_id() 006980D8
i = 3
this_thread::get_id() 00698108
请按任意键继续. . .