I'm writing some threads in Qt and I can't figure out how to pass a predicate to my condition variable to protect against spurious wake up.
Working solution in C++:
std::mutex(mu);
std::condition_variable cond;
std::unique_lock<mutex> alpha_lock(mu);
cond.wait(alpha_lock, [](){ return //some condition;});
alpha_lock.unlock();
//Continue to do stuff...
Qt equivalent:
QMutex mu;
QWaitCondition cond;
QMutexLocker alpha_lock&(mu);
cond.wait(&mu, [](){return //some condition;})
Error:
"no matching member function for call to wait"
Any ideas on how to use a predicate in this Qt code?
As the compiler and @xaxxon have already pointed out, there is no such wait()
overload in QWaitCondition
.
If you want to check a condition before going on you can do it like this
while (!condition()) {
cond.wait(mutex);
}
You can of course put that into a helper function that takes a QWaitCondition
, QMutex
and std::function
if you need this in more places. Or derive from QWaitCondition
adding the overload doing the loop above.