Monday, 29 June 2020

Multithreading:6.Print odd and even numbers using two threads

In this program we are going to look into how to print odd numbers using one thread and even numbers using another thread, the numbers have to be printed in order.
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.
#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