This is a popular question asked for experience programmer while testing multithreading knowledge. We can do it in two ways.
Approach 1: Using lock mechanism
#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
std::mutex m;
int count = 0;
void printEven()
{
cout<< "Entered Even\n"<<endl;
while(count <= 10)
{
m.lock();
if(count%2 == 0)
cout<< count++ << "";
m.unlock();
}
}
void printOdd()
{
cout<< "Entered odd\n"<<endl;
while(count < 10)
{
m.lock();
if(count%2 == 1)
cout<< count++ << "";
m.unlock();
}
}
int main()
{
std::thread t1(printOdd);
std::thread t2(printEven);
t1.join();
t2.join();
return 0;
}
Approach 2: Using Condition variable
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mu;
std::condition_variable cond;
int count = 1;
void PrintOdd()
{
for(; count < 10;)
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker,[](){ return (count%2 == 1); });
std::cout << "From Odd: " << count << std::endl;
count++;
locker.unlock();
cond.notify_all();
}
}
void PrintEven()
{
for(; count < 10;)
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker,[](){ return (count%2 == 0); });
std::cout << "From Even: " << count << std::endl;
count++;
locker.unlock();
cond.notify_all();
}
}
int main()
{
std::thread t1(PrintOdd);
std::thread t2(PrintEven);
t1.join();
t2.join();
return 0;
}