In the below code we have added two methods one to print odd numbers and the other to print even numbers, we call one from t1 and another from t2.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
No comments:
Post a Comment