multithreading - C++: Is the passing of a mutex from a notifier to a waiter seamless? -


in multithreaded environment, have following 2 functions:

std::mutex mtx;     std::condition_variable cv;  void waiter() {    std::unique_lock<std::mutex> lck(mtx);    //...    cv.wait(lck);    //... }  void notifier() {    std::unique_lock<std::mutex> lck(mtx);    //...    cv.notify_one(); } 

assume waiter executes first , waits on condition_variable. notifier executes , notifies waiter. waiter tries reacquire mutex after notifier has released it.

question: possible other thread locks mutex right after notifier has released still before waiter gets it? if yes, has done cannot happen? , if yes, don't understand purpose of condition_variable. purpose should block thread until condition fulfilled. if, after condition fulfilled , thread has been woken up, there chance again condition not fulfilled, what's point?

is possible other thread locks mutex right after notifier has released still before waiter gets it?

yes.

if yes, has done cannot happen?

nothing.

and if yes, don't understand purpose of condition_variable. purpose should block thread until condition fulfilled. if, after condition fulfilled , thread has been woken up, there chance again condition not fulfilled, what's point?

it's more complicated. thread can woken if condition variable not notified @ all. called spurious wakeup (doc).

the point of condition variable block thread until other thread notifies it. in order address "condition not fulfilled when waiting thread gets chance execute" issue waiting thread waits in loop until condition fulfilled. standard library has shortcut that, there void wait( std::unique_lock<std::mutex>& lock, predicate pred ); overload that. see doc.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -