How can I print 12 12 12....continuously using two threads in C 11. can someone please suggest. I have used two functions. One function will print "1" and the second function will print "2" with a condition variable. I don't know whether this is a correct approach or not
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <chrono>
using namespace std;
mutex m;
condition_variable cv;
bool flag = false;
void func1(int i)
{
while(1)
{
unique_lock<mutex> lg(m);
cout << i;
if(flag)
flag = false;
else
flag = true;
lg.unlock();
cv.notify_one();
}
}
void func2(int i)
{
while(1)
{
unique_lock<mutex> ul(m);
cv.wait(ul, [](){return (flag == true) ? true : false;});
cout << i;
ul.unlock();
//this_thread::sleep_for(chrono::milliseconds(2000));
}
}
int main()
{
thread th1(func1, 1);
thread th2(func2, 2);
th1.join();
th2.join();
return 0;
}
CodePudding user response:
You have to make the flag to be toggled by each thread, then each one should wait for the flag to have the correct value. The code below should make the job
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <chrono>
using namespace std;
mutex m;
condition_variable cv;
bool flag = false;
void func1(int i)
{
while (1)
{
unique_lock<mutex> lg(m);
cv.wait(lg, []() {return (flag == false) ? true : false; });
cout << i;
flag = true;
this_thread::sleep_for(chrono::milliseconds(200));
lg.unlock();
cv.notify_one();
}
}
void func2(int i)
{
while (1)
{
unique_lock<mutex> ul(m);
cv.wait(ul, []() {return (flag == true) ? true : false; });
cout << i;
flag = false;
this_thread::sleep_for(chrono::milliseconds(200));
ul.unlock();
cv.notify_one();
}
}
int main()
{
thread th1(func1, 1);
thread th2(func2, 2);
th1.join();
th2.join();
return 0;
}