lundi 29 juin 2020

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

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!

Aucun commentaire:

Enregistrer un commentaire