What happens if i call wait on a notified condition variable

前端 未结 2 1873
臣服心动
臣服心动 2021-01-04 19:16

Suppose I have two threads and one shared c++ 11 condition variable. What whould happen if thread1 call notify and after that thread2 call wait? Will thread2 block forever o

相关标签:
2条回答
  • 2021-01-04 19:46

    Usually both the code that decides to wait and the code that decides to notify share the same mutex. So thread2 will never "miss" the notify from thread1.

    Here's the classic lock-based concurrent queue example:

    void push(int x)
    { 
        lock_guard<mutex> guard{queue_mutex};
        thequeue.push(x);
        not_empty_condition.notify_one();
    }
    
    int pop()
    {
        unique_lock<mutex> guard{queue_mutex};
        not_empty_condition.wait(guard, []{ return !thequeue.empty(); } );
        int x = thequeue.front();
        thequeue.pop();
        return x;
    }
    

    Assume thread1 and thread2 are running push() and pop() respectively. Only one of them will be in the critical section at a time.

    • If thread2 has the lock, either it never waits because the queue is not empty (so "losing" a notify is harmless), or it sits there waiting for a notify (which won't be lost).

    • If thread1 got the lock, it will put an element in the queue; if thread2 was waiting, it will get notified properly; if thread2 was still waiting for the mutex, it will never wait, as there is at least one element on the queue, so losing a notify is harmless.

    In this manner, a notify is only lost if it was not needed in the first place.

    Now, if you have a different usage for condition variables in mind, where "losing" a notification has any consequence, I believe you either have a race condition, or are using the wrong tool altogether.

    0 讨论(0)
  • 2021-01-04 19:49

    Thread2 will block until someone calls notify. Calls to notify release threads that are waiting at the time of the call. If there are no threads waiting, they do nothing. They aren't saved.

    0 讨论(0)
提交回复
热议问题