Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

InterviewGuide 勘误 #128

Open
laoyoutiao237 opened this issue Aug 2, 2023 · 0 comments
Open

InterviewGuide 勘误 #128

laoyoutiao237 opened this issue Aug 2, 2023 · 0 comments

Comments

@laoyoutiao237
Copy link

面试高频算法真题里 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant