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;
}