#include <iostream> #include <string> #include <thread> #include <mutex> #include <condition_variable> using namespace std; std::mutex mu; std::condition_variable cv; std::string data; bool odddone = false; bool evendone = true; int num = 0;//lets start the number with 0; void print_odd() { while (num < 100) { // Wait until main() sends data unique_lock<mutex> lock(mu); cv.wait(lock, [] {return evendone; });//wait till evendone is made true by main thread //thread is adding numbers to data cout << ++num << endl; // Send data back to main() odddone = true; evendone = false; // Manual unlocking is done before notifying, to avoid waking up // the waiting thread only to block again lock.unlock(); cv.notify_all(); } } void print_even() { while (num < 100) { // Wait until main() sends data unique_lock<mutex> lock(mu); cv.wait(lock, [] {return odddone; });//wait till evendone is made true by main thread //thread is adding numbers to data cout << ++num << endl; // Send data back to main() evendone = true; odddone = false; //unlocking before notifying lock.unlock(); cv.notify_all(); } } int main() { thread t1(print_odd); thread t2(print_even); t1.join(); t2.join(); return 1; }