forthespada / InterviewGuide

🔥🔥「InterviewGuide」是阿秀从校园->职场多年计算机自学过程的记录以及学弟学妹们计算机校招&秋招经验总结文章的汇总,包括但不限于C/C++ 、Golang、JavaScript、Vue、操作系统、数据结构、计算机网络、MySQL、Redis等学习总结,坚持学习,持续成长!
https://interviewguide.cn/
Apache License 2.0
5.37k stars 1.45k forks source link

InterviewGuide 勘误 #128

Open laoyoutiao237 opened 1 year ago

laoyoutiao237 commented 1 year ago

面试高频算法真题里 11、写三个线程交替打印ABC 原解答为:

void printa(){
    unique_lock<mutex> lk(mymutex); //此处加锁的位置不对
    int count=0;
    while(count<10){
        while(flag!=0) cv.wait(lk);
        cout<<"thread 1: a"<<endl;
        flag=1;
        cv.notify_all();
        count++;
    }
    cout<<"my thread 1 finish"<<endl;
}

应将加锁位置改为while循环内

void printa(){

    int count=0;
    while(count<10){
        unique_lock<mutex> lk(mymutex); //此处加锁
        while(flag!=0) cv.wait(lk);
        cout<<"thread 1: a"<<endl;
        flag=1;
        cv.notify_all();
        count++;
    }
    cout<<"my thread 1 finish"<<endl;
}