How to use std::mutex in different threads? <p>How to properly write multithreaded code with mutex:</p> <pre><code>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 (); </code></pre> <p>When I call m.unlock() visual studio 2012 raises error R6010. Mutex m2 works fine, because it locks and unlocks in one thread.</p> <p>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.</p> <p>UPD: Replace with conditional_variable and all works fine now. Article: <a href="http://stackoverflow.com/questions/4792449/c0x-has-no-semaphores-how-to-synchronize-threads">C++0x has no semaphores? How to synchronize threads?</a></p>