Hi Everyone, I wrote the following program for alternatively incrementing and doubling a counter(increment first) using boost condition variables. Can any one tell me if this is the correct use of boost condition variables. It is working correctly. I don't understand the use of lock in wait function call. What does condition.wait(lock) mean? For example what is the use of two scoped locks in increment and multiply in this program. How can I avoid them?
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/condition_variable.hpp>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int counter=0;
boost::mutex m1,m2;
bool incremented=false,multiplied=false;
boost::condition_variable c1,c2;
void Increment()
{
{
boost::mutex::scoped_lock lk(m1);
counter++;
incremented = true;
c1.notify_one();
while(!multiplied)
c2.wait(lk);
multiplied=false;
}
}
void Multiply()
{
{
boost::mutex::scoped_lock lk(m2);
while(!incremented)
c1.wait(lk);
incremented = false;
counter = counter*2 ;
multiplied = true;
c2.notify_one();
}
}
void IncrementNtimes(int n){
for(int i=0;i<n;i++){
Increment();
}
}
void MultiplyNtimes(int n){
for(int i=0;i<n;i++){
Multiply();
}
}
int main(int argc, char* argv[])
{
srand ( time(NULL) );
boost::thread thrd1(boost::bind(&IncrementNtimes,20));
boost::thread thrd2(boost::bind(&MultiplyNtimes,20));
thrd1.join();
thrd2.join();
cout<<"Main counter is:"<<counter<<endl;
return 0;
}