[英]Passing a predicate to QWaitCondition?
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. 我在Qt中编写了一些线程,但无法弄清楚如何将谓词传递给我的条件变量以防止虚假唤醒。
Working solution in C++: 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: Qt等效项:
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? 关于如何在此Qt代码中使用谓词的任何想法?
As the compiler and @xaxxon have already pointed out, there is no such wait()
overload in QWaitCondition
. 正如编译器和@xaxxon所指出的那样,
QWaitCondition
没有此类wait()
重载。
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. 当然,您可以将其放到需要
QWaitCondition
, QMutex
和std::function
的辅助函数中,如果需要更多地方的话。 Or derive from QWaitCondition
adding the overload doing the loop above. 或者从
QWaitCondition
派生,并在上面的循环中添加重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.