c++ - Exception thrown when locking boost::unique_lock which is already locked in other thread -


there global object boost::unique_lock. 1 thread locks it. when other thread tries lock exception "already owns mutex" thrown. why happening? expect thread blocked until other thread call unlock.

boost::mutex mutex; boost::unique_lock<boost::mutex> lock(mutex);  static void* scheduller(void* arg) {     boost::this_thread::sleep(boost::posix_time::seconds(5));     lock.lock();         return 0; }  static void* usb(void* arg) {     lock.lock();     boost::this_thread::sleep(boost::posix_time::seconds(20));     return 0; }  int bevent_test() {     lock.unlock();     int = 0;     boost::thread thread1(usb,&a);     boost::thread thread2(scheduller,&a);     boost::this_thread::sleep(boost::posix_time::seconds(100));     return 0;  } 

in bevent_test function i'm doing unlock because unique lock locked in constructor. delays make sure scheduller thread starts after usb thread. when tries lock() exception thrown. why?

your use of unique_lock wrong, in particular objects not supposed shared between different threads, because not thread-safe. yes, sounds weird @ first, make sense, because being thread-safe , providing thread-safety 2 distinct things.

the idea of unique_lock manage locks on mutexes. that, create objects locally only. that's reason locked, seem "work around" unlocking it. however, should rather try use scope/lifetime manage lock.

now, need unique_lock in order use event. yes , no. need one, not same 1 every thread using event. instead, can use different, local lock instances different threads. btw: reason event needs lock while waiting event, lock must released. after receiving event (or timeout), has reacquire lock. in other words, lock serves proxy mutex, offering indirection , added guarantees.

the reason receive exception try lock unique_lock twice. don't think matters same thread, wouldn't same thread. however, when lock mutex (via unique_lock), entering critical section. implies before, weren't in critical section. if unique_lock finds lock held, means in code went wrong, because code seems confused whether inside critical section or not. reason, exception motivation fix code.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -