#include #include #include #include using namespace std ; mutex mutexObj1 ; mutex mutexObj2 ; mutex mutexObj3 ; condition_variable cv; mutex mutexG ; bool var1 = false ; bool var2 = false ; void function3() { for( int i1= 0 ; i1 < 10 ; i1 += 2 ) { unique_lock lk( mutexObj3 ) ; var1 = false ; cout << "i1:" << i1 << endl ; var2 = true ; cv.notify_one(); cv.wait(lk, []{ return var1; }); } //for cout << "Out of the for loop for function 3." << endl ; var2 = true ; cv.notify_one(); } void function4() { for( int i2= 1 ; i2 < 10 ; i2 += 2 ) { unique_lock lk( mutexObj3 ); var2 = false ; cout << "i2--:" << i2 << endl ; var1 = true ; cv.notify_one(); cv.wait(lk, []{ return var2; }); this_thread::sleep_for( chrono::microseconds(1) ); } //for var1 = true ; cv.notify_one(); cout << "Out of the for loop for function 4." << endl ; } void function1() { for( int i1= 0 ; i1 < 10 ; i1 += 2 ) { mutexObj1.lock() ; mutexG.lock() ; cout << "i1:" << i1 << endl ; mutexG.unlock() ; mutexObj1.unlock() ; } } void function2() { for( int i2= 1 ; i2 < 10 ; i2 += 2 ) { mutexObj1.lock() ; mutexG.lock() ; cout << "i2:" << i2 << endl ; mutexG.unlock() ; mutexObj1.unlock() ; //this_thread::sleep_for( chrono::microseconds(1) ); } //for } int main() { //mutexObj2.lock() ; //this_thread::sleep_for( chrono::seconds(2) ); thread th1 ( function1 ) ; thread th2 ( function2 ) ; // thread th1 ( function3 ) ; // thread th2 ( function4 ) ; //this_thread::sleep_for( chrono::seconds(5) ); //mutexObj1.unlock() ; mutexObj2.unlock() ; th1.join() ; th2.join() ; return 0 ; }