Open laoyoutiao237 opened 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; }
面试高频算法真题里 11、写三个线程交替打印ABC 原解答为:
应将加锁位置改为while循环内