I'm trying to sync two threads using condition_variable in c++11. I'm a using eclipse under ubuntu, and everything is compiled with g++. Both threads are in the same class. The first thread increments a private variable of the class:
void Test::test::Loop()
{
int loops = 48;
while (loops > 0)
{
std::lock_guard<std::mutex> lock(this->m);
this->index++;
// Simulate work
std::this_thread::sleep_for(std::chrono::milliseconds(10));
this->Processed = true;
this->c.notify_one();
loops--;
}
return;
}
As a first test I'd like to display this->index in the other thread:
void Test::test::Process()
{
while(this->ProcessData)
{
std::unique_lock<std::mutex> lock(this->m);
while(!this->Processed)
this->c.wait(lock);
printf("\n%d", this->index);
fflush(stdout);
this->Processed = false;
this->m.unlock();
this->c.notify_one();
}
return;
}
I also tried with this->c.wait(lock, [this] { return this->Processed;}). The result is that the program displays only the number 1, and never stops... What am I doing wrong? This is the fist time I really used condition_variable, but as far as I understood c.notify_one() should allow the second thread to display the variable for each iteration.
Sorry if the question's already been asked, but I didn't really find anything similar. Thanks for your help.
Aucun commentaire:
Enregistrer un commentaire