condition_variable_any 如此的不靠谱

TheNewIpad 2014-02-28 02:40:36
在工程中使用了condition_variable_any::timed_wait, 由于当时对此完全不了解。出现了BUG。


如下代码,请猜测, 输出的nRecv的值。
请注意,我先启动的testcallback_consumer。

#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;
}
...全文
228 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
vipcxj 2014-03-04
  • 打赏
  • 举报
回复
  • 打赏
  • 举报
回复
TheNewIpad 2014-03-04
  • 打赏
  • 举报
回复
来人结贴了。

5,530

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 模式及实现
社区管理员
  • 模式及实现社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧