2

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?

Community
  • 1
  • 1
Alexey
  • 593
  • 1
  • 5
  • 14
  • Where else is mutex m locked/unlocked in your program. – v78 Sep 24 '16 at 09:14
  • In third thread this mutex is locks, do some work and unlocks. Inside this thread everything looks fine. I commented it and nothing changed (error R6010 raised). – Alexey Sep 24 '16 at 09:51
  • Note that the parentheses around the increment and decrement of `reference` are not needed (and distracting). – Pete Becker Sep 24 '16 at 13:33

1 Answers1

1

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?

Community
  • 1
  • 1
Marek Fekete
  • 641
  • 3
  • 16