boost::thread (barrier)


#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
请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值