Hey this should be a pretty straightforward question. Simply put:
- Want to run a function in another thread.
- Need to wait for the function to finish.
- Do not want to freeze the thread though while waiting.
- In other words, I'd like to use an eventloop.
Here is the freezing example:
extern void sneed()
{
QEventLoop wait;
wait.exec();
}
int main( int argc, char *argv[] )
{
QApplication a(argc, argv);
{
// this starts a tui
QConsoleToolkit::s_CursesController.start( QCD::CursesEngine::Engine_Thread_Stdout_Monitor );
}
ct_Start( "Sneed" );
QFuture<void> ff = QtConcurrent::run(sneed);
ff.waitForFinished(); // This freezes the tui
ct_Finish( "Chuck" );
}
I tried to use a QEventLoop in the main thread instead of ff.waitForFinished(), but I could not figure out how I could emit a signal when ff was finished, because QFuture isnt a QObject, and has no finished signal that I could bind to:
https://doc.qt.io/qt-6/qfuture.html
I tried passing a QObject via reference to emit a signal from it instead, but couldnt get it to compile.
What am I missing here?
The solution comes from a simple class called QFutureWatcher:
doc.qt.io/qt-5/qfuturewatcher.html
Here is some sample code for running lambda's in a different thread, and receiving its value.
using the function would look like this:
Note:
ct_Debug ct_Start ct_Finishare not found in the Qt framework. They are debugging macros for a TUI.