I am trying to synchronize the increment of the variable i alternatively with main thread and thread t. Below programme is blocked after few iterations. I couldn't figure out what the problem is.
#include <iostream>
#include <thread>
#include <algorithm>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mu;
condition_variable cv_main;
condition_variable cv_thr;
bool make_main_work;
bool make_thread_work;
void fun(int& i)
{
unique_lock<mutex> ul(mu);
cv_thr.wait(ul, [](){ return make_thread_work;});
cout << "fun: " <<++i<<endl;
make_thread_work = false;
ul.unlock();
make_main_work = true;
cv_main.notify_one();
}
int main()
{
int i =0;
make_thread_work = false;
make_main_work = true;
thread t(fun, std::ref(i));
for(int k =1; k<100; ++k)
{
unique_lock<mutex> ul(mu);
cv_main.wait(ul, [](){return make_main_work;});
make_main_work = false;
cout << "main: "<<++i << endl;
ul.unlock();
make_thread_work = true;
cv_thr.notify_one();
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire