boost条件变量使用示例及性能测试

      搞教程时弄了段代码,不知道要放在哪里,就贴这吧。
      两个线程玩踢球游戏。最后打印球踢了几回。这段代码示范了条件变量的正确使用方法,以及如何优雅关闭可能正在wait条件变量的线程。在windows和Linux下测试都大概是10几万次每秒。条件变量要改变线程的运行状态,故需要系统调用,效率还是比较低的。这点要注意。
========================================================================
#include <iostream>
#include <boost/thread.hpp>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

using namespace std;

bool running_flag = true;
int cnt = 0;
boost::mutex mtx;
boost::condition_variable cond;
bool ball = true;

void run1(){
      int i = 0;
      while(running_flag){
            boost::mutex::scoped_lock lock(mtx);
            while (ball != true && running_flag){
                  cond.wait(lock);                 
            }
            ++i; ++cnt;
            if (running_flag){
                  ball = false;
                  cond.notify_all();                 
            }
         
      boost::mutex::scoped_lock lock(mtx);
      cout << i << endl;
}

void run2(){
      int i = 0;
      while(running_flag){
            boost::mutex::scoped_lock lock(mtx);
            while (ball != false && running_flag){
                  cond.wait(lock);                 
            }
            ++i; ++cnt;
            if (running_flag){
                  ball = true;
                  cond.notify_all();                 
            }
      }
      boost::mutex::scoped_lock lock(mtx);
      cout << i << endl;
}

int main(int argc, char* argv[]){
      boost::thread_group grp;
      grp.create_thread(run1);
      grp.create_thread(run2);

#ifdef WIN32
      Sleep(1000);
#else
      sleep(1);
#endif
      running_flag = false;
      {
            boost::mutex::scoped_lock lock(mtx);
            cond.notify_all();
      }
      grp.join_all();
      cout << cnt << endl;
      return 0;
}

========================================================================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值