[英]Detect that “I'm running” in Qt GUI event thread
I have this function to update some GUI stuff: 我有这个功能来更新一些GUI的东西:
void SavedConnections::renderList()
{
// Do GUI stuff! Must run in Qt thread!!!
...
}
I need to ensure that this function isn't called from other threads. 我需要确保不从其他线程调用此函数。 What I plan to do is to defer it into event loop and raise a warning: 我打算做的是将它推迟到事件循环并发出警告:
void SavedConnections::renderList()
{
if(!this_thread_is_Qt_GUI_thread()) {
qDebug()<< "Warning: GUI operation attempted from non GUI thread!\n";
QCoreApplication::postEvent(this, new UpdateGUIEvent());
return;
}
// Do GUI stuff! Must run in Qt thread!!!
...
}
This pattern is also very convenient to make methods that are guaranteed to run asynchronously in GUI thread without any ugly syntax. 这种模式也非常方便,可以保证在GUI线程中异步运行的方法没有任何丑陋的语法。 I already asked similar question about Java's ExecutorService . 我已经问过关于Java的ExecutorService的类似问题 。
You can check if the current thread is the thread your object lives in: 您可以检查当前线程是否是您的对象所在的线程:
if (QThread::currentThread() != this->thread()) {
// Called from different thread
}
Note that this might not be the main GUI-Thread ! 请注意, 这可能不是主要的GUI-Thread ! It is the thread this
lives in (see QObject Thread affinity) . 它是线程this
住在(见QObject的线程关联) 。 If you don't change it using QObject::moveToThread
, it is the thread the object was created in. 如果不使用QObject::moveToThread
更改它,则它是创建对象的线程。
This is also what QCoreApplication::postEvent
uses to determine into which thread the event should be posted. 这也是QCoreApplication::postEvent
用于确定事件应发布到哪个线程的内容。 The targeted Thread must run a QEventLoop
to respond to the event. 目标Thread必须运行QEventLoop
才能响应该事件。
So checking for the main-GUI-Thread ( qApp->thread()
), but posting to this
's thread might not work, if your object does not live in the main-GUI-Thread. 因此,检查main-GUI-Thread( qApp->thread()
),但如果您的对象不在主GUI-Thread中,则发布this
线程可能不起作用。 However, if you do GUI stuff there, it should anyway live in the GUI-Thread 但是,如果你在那里做GUI的东西,它应该存在于GUI-Thread中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.