I am having some trouble conceptualizing how unique_lock is supposed to operate across threads. I tried to make a quick example to recreate something that I would normally use a condition_variable for.
#include <mutex> #include <thread> using namespace std; mutex m; unique_lock<mutex>* mLock; void funcA() { //thread 2 mLock->lock();//blocks until unlock?Access violation reading location 0x0000000000000000. } int _tmain(int argc, _TCHAR* argv[]) { //thread 1 mLock = new unique_lock<mutex>(m); mLock->release();//Allows .lock() to be taken by a different thread? auto a = std::thread(funcA); std::chrono::milliseconds dura(1000);//make sure thread is running std::this_thread::sleep_for(dura); mLock->unlock();//Unlocks thread 2's lock? a.join(); return 0; }
unique_lockis just abstraction for mutex ownership. All synchronization it does is locking and unlocking mutex.unique_lockis not meant to be shared, only to hold a lock across a specific scope (it's just a RAII wrapper for the mutex lock, nothing more). Of course you can try to misuse it, and to be blunt as far as misuse goes I think you really nailed it. ;)