简体   繁体   English

从另一个线程唤醒QThread :: exec()

[英]Wake up QThread::exec() from another thread

Consider MyThread that derives from QThread and implements it's run() routine like this 考虑从QThread派生的MyThread ,并像这样实现它的run()例程

void MyThread::run() {
  QThread::exec();
}

or equivalently 或者等价的

void MyThread::run() {
  QEventLoop eventLoop(this);
  eventLoop.exec();
}

In this state how does one cause the 'exec' to return by some action in another thread? 在这种状态下,如何通过另一个线程中的某个动作使'exec'返回?

To consider the opposite case: without polling, how might one post an event from the thread back to the main thread? 考虑相反的情况:没有轮询,如何将一个事件从线程发回主线程?

Apparently signals that are emitted from a thread are handled in the same thread. 显然,从线程发出的信号在同一个线程中处理。

You seem to have some misunderstanding how QThreads are supposed to work. 您似乎对QThreads应该如何工作有一些误解。 Unfortunately, you are not alone with this. 不幸的是,你并不孤单。

The first thing to do is to read about the correct usage in here: 首先要做的是在这里阅读正确的用法:

How To Really, Truly Use QThreads; 如何真正地,真正使用QThreads; The Full Explanation 完整解释

So, what you should write is something like this: 所以,你应该写的是这样的:

QThread* thread1 = new QThread;
QThread* thread2 = new QThread;
Task1* task1 = new Task1();
task1->moveToThread(thread1);
Task2* task2 = new Task2();
task2->moveToThread(thread2);
connect(task2, SIGNAL(finished()), thread1, SLOT(quit()));
connect(thread2, SIGNAL(started()), task2, SLOT(process()));
thread1->start();
thread2->start();

As you can see, I am using the quit() slot just like the aforementioned example. 正如您所看到的,我正在使用quit()插槽,就像上面提到的示例一样。 You will need to use then emit finished() in your task2 which tries to terminate thread1 or vice versa. 您将需要在task2中使用然后emit finished() ,尝试终止thread1,反之亦然。

QEventLoop has a slot quit that you can call. QEventLoop有一个可以调用的插槽quit If you put a reference to the eventloop in your mythread, you can then use that to call the slot. 如果您在mythread中添加对eventloop的引用,则可以使用它来调用插槽。

Signals/slots can be used in a cross thread fashion. 信号/槽可以以跨线程方式使用。 More information here: Signals and Slots Across Threads 更多信息: 跨线程的信号和插槽

QMetaObject::invokeMethod( eventloop, "quit", Qt::QueuedConnection)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM