我正在尝试使用以下代码来测试同步提升条件变量,此代码确实同步。但它只显示 4 个值这里有什么问题?,我该如何解决?
在 Windows 7 上使用 vs 2012
提前致谢。
#include <iostream>
#include <queue>
#include "boost\thread.hpp"
#include "boost\timer.hpp"
using namespace std;
int counter;
boost::mutex m;
boost::condition_variable CworkDone;
bool workdone = true;
bool procOn = true;
void display()
{
while (procOn == true)
{
boost::mutex::scoped_lock lock(m);
if (workdone)
{
cout<<counter<<endl;
CworkDone.notify_one();
workdone = false;
}
else
{
CworkDone.wait(lock);
}
}
}
void increment()
{
for(int i = 0 ; i <10 ; ++i)
{
boost::mutex::scoped_lock lock(m);
if (!workdone)
{
boost::this_thread::sleep(boost::posix_time::millisec(500));
++counter;
workdone = true;
CworkDone.notify_one();
}
else
{
CworkDone.wait(lock);
}
}
procOn = false;
}
int main()
{
boost::thread dispthread(display);
boost::thread incthread(increment);
dispthread.join();
incthread.join();
}