#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
using namespace std;
int num = 1;
#define NUM 20
condition_variable odd;
condition_variable even;
mutex mut;
void thread_odd()
{
while(num < NUM -1)
{
if(num%2 != 1)
{
unique_lock<mutex> lock(mut);
odd.wait(lock);
}
cout<<"ODD : "<<num<<endl;
num++;
even.notify_all(); // Line X
}
}
void thread_even()
{
while(num < NUM )
{
if(num%2 != 0)
{
unique_lock<mutex> lock(mut);
even.wait(lock);
}
cout<<"EVEN : "<<num<<endl;
num++;
odd.notify_all();
}
}
int main()
{
thread t1(thread_odd), t2(thread_even);
t1.join();
t2.join();
return 0;
}
/* Above is the program to print ODD & EVEN numbers in synchronized manner ( one by one ) . The code is working fine most of the time . But it is getting into a deadlock situation sometimes . That is happening when odd thread is hitting notify_all but before the even thread wakes up it odd thread acquires the lock and then as it finds wait condition it goes into wait while the even thread hasn't wake up . Leaving a dealock situation . I tried replacing notify_all to notify_one , but the problem still persists . Is there any change in the design required ? Or is there anything which I am missing completely ? */