I am learning multi threading concept.I am trying to print sequence of number using 3 thread(using 2 thread its working).My program hang after print 1,2,3.
Code:
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
std::mutex MUT;
std::condition_variable cv;
enum class table {EVEN,ODD,HALF};
table t=table::ODD;
void even(int &r)
{
while(r<20)
{
unique_lock<mutex>l1(MUT);
cv.wait(l1,[](){ return t==table::EVEN;});
cout<<"Thread 2 "<<r++<<endl;
t=table::HALF;
l1.unlock();
cv.notify_one();
}
}
void odd(int &s)
{
while(s<20)
{
unique_lock<mutex>l2(MUT);
cv.wait(l2,[](){ return t==table::ODD;});
cout<<"Thread 1 "<<s++<<endl;
t=table::EVEN;
l2.unlock();
cv.notify_one();
}
}
void half(int &u)
{
while(u<20)
{
unique_lock<mutex>l3(MUT);
cv.wait(l3,[](){ return t==table::HALF;});
cout<<"Thread 3 "<<u++<<endl;
t=table::ODD;
l3.unlock();
cv.notify_one();
}
}
int main()
{
int x=1;
thread t1(odd,ref(x));
thread t2(even,ref(x));
thread t3(half,ref(x));
t1.join();
t2.join();
t3.join();
return 0;
}
Output shown:
Thread 1 1
Thread 2 2
Thread 3 3
After this no output.
Please let me know where i am doing wrong using 3 threads.
Thanks for your help
Aucun commentaire:
Enregistrer un commentaire