Tom*_*ica 3 c++ qt multithreading
我有这个功能来更新一些GUI的东西:
void SavedConnections::renderList()
{
// Do GUI stuff! Must run in Qt thread!!!
...
}
Run Code Online (Sandbox Code Playgroud)
我需要确保不从其他线程调用此函数.我打算做的是将它推迟到事件循环并发出警告:
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!!!
...
}
Run Code Online (Sandbox Code Playgroud)
这种模式也非常方便,可以保证在GUI线程中异步运行的方法没有任何丑陋的语法.我已经问过关于Java的ExecutorService的类似问题.
您可以检查当前线程是否是您的对象所在的线程:
if (QThread::currentThread() != this->thread()) {
// Called from different thread
}
Run Code Online (Sandbox Code Playgroud)
请注意,这可能不是主要的GUI-Thread!它是线程this所在(参见QObject Thread affinity).如果您不使用它来更改它QObject::moveToThread,则它是创建对象的线程.
这也是QCoreApplication::postEvent用于确定应该发布事件的线程的内容.目标Thread必须运行a QEventLoop来响应事件.
因此,如果您的对象不在主GUI-Thread中qApp->thread(),那么检查main-GUI-Thread(),但是发布到this的线程可能不起作用.但是,如果你在那里做GUI的东西,它应该存在于GUI-Thread中
| 归档时间: |
|
| 查看次数: |
3547 次 |
| 最近记录: |