搞教程时弄了段代码,不知道要放在哪里,就贴这吧。
两个线程玩踢球游戏。最后打印球踢了几回。这段代码示范了条件变量的正确使用方法,以及如何优雅关闭可能正在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;
}
========================================================================