开发者

C++: thread sync

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 m开发者_JAVA百科ymutex.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();
...


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.

Google for "c++ RAII":

With mymutex.lock() you are "manually" locking the mutex. (And later have to unlock it "manually".)

scoped_lock is a helper class that does locking - and automatic unlocking at end of its scope - for you.


boost::mutex::scoped_lock mutex2lock(mutex2);

This should, if I understand correctly, but a big lock on mutex2 that'll last the length of your Mutex.

Likely you want that lock within the context of the second thread, but I don't much understand why condition_variable wants it.

In fact, it seems that condition_variable itself is a bit wrong for what you are doing, reading the documentation:

Atomically call lock.unlock() and blocks the current thread. The thread will unblock when notified by a call to this->notify_one() or this->notify_all(), or spuriously

That description seems to me that it can just unlock when it feels it can run (likely based on time) It seems you would likely need to check to see if you the list is valid, and if not, call wait again, if you plan to use condition_variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜