Why do both the notify and wait function of a std::condition_variable need a locked mutex

后端 未结 3 1936
名媛妹妹
名媛妹妹 2020-12-19 08:31

On my neverending quest to understand std::contion_variables I\'ve run into the following. On this page it says the following:

void print_id (i         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-19 09:10

    What you're missing is that wait unlocks the mutex and then waits for the signal on cv.

    It locks the mutex again before returning.

    You could have found this out by clicking on wait on the page where you found the example:

    At the moment of blocking the thread, the function automatically calls lck.unlock(), allowing other locked threads to continue.

    Once notified (explicitly, by some other thread), the function unblocks and calls lck.lock(), leaving lck in the same state as when the function was called.

提交回复
热议问题