i am trying following code to test boost condition variable for synchoronization,
this code does sync. but it shows only 4 values what is wrong here ? , how i can fix it ?
using vs 2012 on windows 7
thanks in advance.
#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();
}
The problem is a class producer/consumer problem. Your code as it stands doesn’t really make sense – you cannot use a single condition variable for waiting on both sides, (remember you call notify then wait – on the same condition, in the same context.) So anything can happen.
You need to refactor your code to use two condition variables, one for the producer, one for the consumer, for example:
EDIT: Updated with a pure c++11 implementation which should be correct.
So now what happens is, the consumer waits on it’s condition (and only the producer will call
notify()on this), and the producer, once it has produced something calls this notify which will wake the client up. The client will then callnotify()to wake the producer up.The above updated approach should not suffer the spurious wake up problem as I highlighted before. This negates the need for a
timed_wait.