Question

I have a producer and consumer thread that are being created from main. They perform correctly well, except for the cout statement

class myclass{
int x;
// stuff
}

void foo1(myclass* ob){
setX(ob->x);
// stuff
}

void foo2(myclass* ob){

cout << ob->x << endl; // ONLY THIS DOESN'T EXECUTE

ob->getX();
// stuff
}

int main(){
myclass* ob = new myclass();
boost::thread producer_thread(boost::bind(foo1, ob));
boost::thread consumer_thread(boost::bind(foo2, ob));
// stuff

producer_thread.join();
consumer_thread.join();

}

Everything works fine (including showX that displays x, except for the cout. What's wrong?

Was it helpful?

Solution

Your threads are sharing the object without actually any lock on it. producer is not exiting before consumer started accessing the object. Using producer_thread.join() before boost::thread consumer_thread(boost::bind(foo2, ob)) should resolve this, which is not the best fix. Using mutex locks will be ideal.

OTHER TIPS

Adding to the previous answer, you can also use a state variable or condition variable to ensure that your object is not getting written upon / processed by a thread when some other thread is working on it. In other words, you can have a state variable whose value is changed by each function to a unique number upon completion and each function will start operating when the state variable is assumes the value that the previous function is supposed to set it to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top