Condition variable deadlock

后端 未结 2 1511
暗喜
暗喜 2020-12-19 07:16

I have a problem with a deadlock in my code related to the use of condition variables. This is more of a design question than a pure code question. I have no problem actuall

2条回答
  •  长情又很酷
    2020-12-19 07:55

    During the period just before Thread A waits on condition variable it must be holding a mutex. The easiest solution is to make sure that Thread B is holding the same mutex at the time it calls notify_all. So something like this:

    std::mutex m;
    std::condition_variable cv;
    int the_condition = 0;
    
    Thread A: {
      std::unique_lock lock(m);
      do something
      while (the_condition == 0) {
        cv.wait(lock);
      }
      now the_condition != 0 and thread A has the mutex
      do something else
    } // releases the mutex;
    
    Thread B: {
      std::unique_lock lock(m);
      do something that makes the_condition != 0
      cv.notify_all();
    } // releases the mutex
    

    This guarantees that Thread B only does the notify_all() either before Thread A acquires the mutex or while Thread A is waiting on the condition variable.

    The other key here, though, is the while loop waiting for the_condition to become true. Once A has the mutex it should not be possible for any other thread to change the_condition until A has tested the_condition, found it false, and started waiting (thus releasing the mutex).

    The point is: what you are really waiting for is for the value of the_condition to become non-zero, the std::condition_variable::notify_all is just telling you that thread B thinks thread A should wake up and retest.

提交回复
热议问题