Reputation: 683
How to properly write multithreaded code with mutex:
std::mutex m, m2;
... thread
m2.lock();
if ((++reference) == 1) m.lock();
m2.unlock();
... differenet thread
m2.lock();
if ((reference--) == 0) m.unlock(); // error here
m2.unlock ();
When I call m.unlock() visual studio 2012 raises error R6010. Mutex m2 works fine, because it locks and unlocks in one thread.
I tried to replace code with std::contidional_variable, but its not notified at start and first enter to cond_var.wait_one waits infinitely.
UPD: Replace with conditional_variable and all works fine now. Article: C++0x has no semaphores? How to synchronize threads?
Upvotes: 2
Views: 2417
Reputation: 641
Mutex needs to be unlocked by the owning thread (the thread that locked it):
If the mutex is not currently locked by the calling thread, it causes undefined behavior. (http://www.cplusplus.com/reference/mutex/mutex/unlock/)
You'll need to use conditional variable - I think building a semaphore implementation around it will be nice in your case. See the accepted answer here: C++0x has no semaphores? How to synchronize threads?
Upvotes: 1