I am trying to use an std::condition_variable from C++11 for a data transaction between between UI thread & worker thread.
Situation:m_calculated_value is a value which calculated after a complex logic. This is required on a trigger of a event from the UI thread. UI thread calls MyClass::GetCalculatedValue to fetch the value of m_calculated_value which needs to be calculated by the worker thread function that is MyClass::ThreadFunctionToCalculateValue.
Code:
std::mutex m_mutex;
std::condition_variable m_my_condition_variable;
bool m_value_ready;
unsigned int m_calculated_value;
// Gets called from UI thread
unsigned int MyClass::GetCalculatedValue() {
std::unique_lock<std::mutex> lock(m_mutex);
m_value_ready = false;
m_my_condition_variable.wait(lock, std::bind(&MyClass::IsValueReady, this));
return m_calculated_value;
}
bool MyClass::IsValueReady() {
return m_value_ready;
}
// Gets called from an std::thread or worker thread
void MyClass::ThreadFunctionToCalculateValue() {
std::unique_lock<std::mutex> lock(m_mutex);
m_calculated_value = ComplexLogicToCalculateValue();
m_value_ready = true;
m_my_condition_variable.notify_one();
}
Problem:
But the problem is that m_my_condition_variable.wait never returns.
Question:
What am I doing wrong here?
Is it a correct approach to make UI thread wait on a condition variable signal from worker thread? How do I get out of a situation where the condition_variable never triggers due to an error in the worker thread function? Is there a way I can somehow use a timeout here?
Trying to understand how it works:
I see in many examples they use a while loop checking the state of a boolean variable around a condition_var.wait. Whats the point of loop around on a variable? Cant I expect m_my_condition_variable to return out of wait when notify_one is called from other thread ?
wait()with the predicate. Hence they basically reimplemented that one. Regardless, for your use case you should rather use a future, not an condition variable. - Ext3hm_calculated_valueto be ready with the required value whenMyClass::GetCalculatedValuereturns. this looks to me like a typical case of signalling between threads to tell that the data is ready. @Wxt3h Dont you think so as well? How will a future help here? Can you please elaborate a little more? - TheWaterProgrammerComplexLogicToCalculateValue()take a long time? You could call that before taking the lock and assign it to a local variable. Only then take the lock and assign that local variable to the class memberm_calculated_value. Not sure if this relates to your issue at all though. - Galik