5,530
社区成员
发帖
与我相关
我的任务
分享
#include <boost/thread.hpp>
#include <iostream>
#include <stdlib.h>
using namespace std;
boost::recursive_mutex g_mtx;
boost::condition_variable_any g_cnd;
bool g_bCOntinue = true;
void testcallback_product()
{
//模拟生产者1000次
for (int i = 0; i < 1000; i++)
{
//boost::this_thread::sleep(boost::posix_time::milliseconds(1));
boost::unique_lock<boost::recursive_mutex> lock (g_mtx);
g_cnd.notify_one();
}
g_bCOntinue = false;
}
// 首先启动该函数
void testcallback_consumer()
{
int nRec = 0;
bool bRet = false;
while( g_bCOntinue )
{
bRet = false;
boost::unique_lock<boost::recursive_mutex> lock (g_mtx);
while(!bRet)
{
bRet = g_cnd.timed_wait(lock, boost::posix_time::milliseconds(50));
if (bRet)
{
nRec++;
}
}
}
cout<<"nRecv == "<<nRec<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
boost::thread hC(&testcallback_consumer);
boost::this_thread::sleep(boost::posix_time::milliseconds(10));
boost::thread hP(&testcallback_product);
hP.join();
hC.join();
system("pause");
return 0;
}