I'm making an emulator and I need to run the loop that executes instructions in another thread (preferably with QtConcurrent). I am currently doing it like this
#include <QtConcurrent/QtConcurrentRun>
#include <QThread>
QFutureWatcher<void> futureWatcher;
bool running = false;
void MainWindow::startExecution() {
running = true;
futureWatcher.setFuture(QtConcurrent::run([this]() {
while(running){
qDebug() << "Physical Thread ID: " << QThread::currentThreadId();
QThread::msleep(100);
//execute instructions
}
}));
}
void MainWindow::stopExecution()
{
running = false;
futureWatcher.waitForFinished();
}
The issue is every time that futureWatcher
is run, it starts running in another thread. And after 8 runs (or how many threads my CPU has) the futureWatcher
won't run anymore. I proved this by doing this:
qDebug() << "Physical Thread ID: " << QThread::currentThreadId();
This is called as soon as the futureWatcher
starts.
Snippet of the output:
called from Physical Thread ID: 0x2768
Physical Thread ID: 0x8c4
called from Physical Thread ID: 0x2768
Physical Thread ID: 0x1414
called from Physical Thread ID: 0x2768
Physical Thread ID: 0x20d0
called from Physical Thread ID: 0x2768
Physical Thread ID: 0x2768
called from Physical Thread ID: 0x2768
Physical Thread ID: 0x2768
called from Physical Thread ID: 0x2768
Physical Thread ID: 0x2768
As soon as the threads are the same, it no longer behaves correctly and the loop doesn't run when setFuture
is called, but it is actually run when futureWatcher.waitForFinished();
is called in stopExecution()
.
I only need 2 threads. One is the main thread and the other for the execution. Is there a way to always run the future watcher in the same second thread? What other solutions can I use?
I found an error. In the function that actually executes instructions there is one specific condition where that function calls
stopExecution
. I believe because that is called from the same thread that thefutureWatcher
is running, whenfutureWatcher.waitForFinished();
is called, the next timefutureWatcher.setFuture
is called it is started on another thread. This assumption is based on testing the code with and without the condition that callsstopExecution
. I solved the issue by replacing everystopExecution
call from inside the futureWatcher withrunning = false;
. Now the code works as intended. The previous solution with thread pools is unnecessary.