Question

I am trying to synchronize two thread (working on the same C++ map) using the Boost library. I must tell that I am not an expert in C++ and I find the boost documentation quite hard to understand.

What I want to achieve, is something like this:

#Thread 1
get access to the map
put in something
release access 

#Thread 2
wait until map is empty
when it's not empty anymore, wake up and gain access
perform operations on one entry of the map
leave access to somebody else

I tried to use Mutex and condition_variables, but the code was not working properly. In specific, when thread2 was waking up (after waiting the cond. variable), it was not gaining directly access to the map, but there was somebody else that got access and emptied the map. Therefore, I got segmentation fault, because I was expecting the map to be full while it was empty when I accessed it.

In addition, I would like to understand the difference between something like mymutex.lock() and invokations like boost::mutex::scoped_lock scopedLock(mutex_); or unique_lock.

Thanks for teaching :)

EDIT: here I tried to extract the relevant parts of my code. Since I did not understand very well how sync works, it may not make much sense...

//COMMON PART
boost::mutex mutex1;
boost::mutex mutex2;
boost::condition_variable cond;
boost::mutex::scoped_lock mutex2lock(mutex2);

//THREAD 1
...
if(someCondition){
    mutex1.lock();
    map[id]=message;
    cond.notify_one();
    mutex1.unlock();
}
...


//THREAD 2
...
cond.wait(mutex2lock);
mutex.lock();
//Perform operation on map[id]
doSomething(map[id]));
mutex.unlock();
...

No correct solution

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