Question

Consider MyThread that derives from QThread and implements it's run() routine like this

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?

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.

Was it helpful?

Solution

You seem to have some misunderstanding how QThreads are supposed to work. 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; 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. You will need to use then emit finished() in your task2 which tries to terminate thread1 or vice versa.

OTHER TIPS

QEventLoop has a slot quit that you can call. If you put a reference to the eventloop in your mythread, you can then use that to call the slot.

Signals/slots can be used in a cross thread fashion. More information here: Signals and Slots Across Threads

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top