what happen between after notify_all() and before wait() get the lock?

≯℡__Kan透↙ 提交于 2021-01-29 08:34:49

问题


I test the std::condition_variable using the below code:

class CondWait{
public:
    std::condition_variable cv;
    std::mutex mu;
    int i=0;
public:
    void mainTask(){
        std::unique_lock<std::mutex> lk(mu);
        cv.wait(lk);
        i++;
        std::cout<<"main task, "<<i<<std::endl;
    }
    void notifyTask(){

        std::unique_lock<std::mutex> lk(mu);
        i = 0;
        std::cout<<"notify task, "<<i<<std::endl;
        cv.notify_one();
        std::cout<<"notify task, sleep 5 sec"<<std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
};
int main()
{
    CondWait condwait;
    std::thread t1(&CondWait::mainTask,&condwait);
    std::thread t2(&CondWait::notifyTask,&condwait);
    t1.join();
    t2.join();

    return 0;
}

Sometimes, the output is below and the program is blocked:

notify task, 0
notify task, sleep 5 sec

Sometimes, the program will run well,i.e. after 5 seconds of sleep, it will output main task, 1, the complete output is:

notify task, 0
notify task, sleep 5 sec
main task, 1

In my opinion, int the notifyTask thread, the mutex is still used after notify_one, so the wait in the mainTask cannot lock the mutex. But I don't know what will happen next, why the example will have an ambiguity performance. Could you please provide some advice? Thanks a lot!


回答1:


Since you start both threads concurrently perhaps a situation occurs when cv.notify_one() is called before cv.wait() in mainTask and since no threads are waiting yet, the function does nothing. After that, wait() is executed and hangs waiting for a notification



来源:https://stackoverflow.com/questions/62636456/what-happen-between-after-notify-all-and-before-wait-get-the-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!