boost - C++: thread sync -


i trying synchronize 2 thread (working on same c++ map) using boost library. must tell not expert in c++ , find boost documentation quite hard understand.

what want achieve, this:

#thread 1 access map put in release access   #thread 2 wait until map empty when it's not empty anymore, wake , gain access perform operations on 1 entry of map leave access else 

i tried use mutex , condition_variables, code not working properly. in specific, when thread2 waking (after waiting cond. variable), not gaining directly access map, there else got access , emptied map. therefore, got segmentation fault, because expecting map full while empty when accessed it.

in addition, understand difference between mymutex.lock() , invokations boost::mutex::scoped_lock scopedlock(mutex_); or unique_lock.

thanks teaching :)

edit: here tried extract relevant parts of code. since did not understand how sync works, may not make 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(); ... 

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

this should, if understand correctly, big lock on mutex2 that'll last length of mutex.

likely want lock within context of second thread, don't understand why condition_variable wants it.

in fact, seems condition_variable bit wrong doing, reading documentation:

atomically call lock.unlock() , blocks current thread. thread unblock when notified call this->notify_one() or this->notify_all(), or spuriously

that description seems me can unlock when feels can run (likely based on time) seems need check see if list valid, , if not, call wait again, if plan use condition_variable.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -