代码
# include <iostream>
# include <thread>
# include <mutex>
# include <condition_variable>
using namespace std;
mutex mtx;
condition_variable cv;
int flag= 0 ;
void A ( ) {
unique_lock< mutex> lk ( mtx) ;
int count= 0 ;
while ( count< 10 ) {
while ( flag!= 0 ) cv. wait ( lk) ;
cout<< "thread1 : a" << endl;
count++ ;
this_thread:: sleep_for ( chrono:: milliseconds ( 500 ) ) ;
flag= 1 ;
cv. notify_all ( ) ;
}
cout<< "thread 1 finish" << endl;
}
void B ( ) {
unique_lock< mutex> lk ( mtx) ;
int count= 0 ;
while ( count< 10 ) {
while ( flag!= 1 ) cv. wait ( lk) ;
cout<< "thread 2 : b" << endl;
this_thread:: sleep_for ( chrono:: milliseconds ( 500 ) ) ;
flag= 2 ;
cv. notify_all ( ) ;
count++ ;
}
cout<< "thread 2 finished" << endl;
}
void C ( ) {
unique_lock< mutex> lk ( mtx) ;
int count= 0 ;
while ( count< 10 ) {
while ( flag!= 2 ) cv. wait ( lk) ;
cout<< "thread 3 : c" << endl;
this_thread:: sleep_for ( chrono:: milliseconds ( 500 ) ) ;
flag= 0 ;
cv. notify_all ( ) ;
count++ ;
}
cout<< "thread 3 finished" << endl;
}
int main ( ) {
thread t1 ( A) ;
thread t2 ( B) ;
thread t3 ( C) ;
t1. join ( ) ;
t2. join ( ) ;
t3. join ( ) ;
return 0 ;
}
结果