I'm using QThread
's event loop to communicate with worker threads.
I noticed that I can't use the thread's event loop just after a start
.
The following code does not work, as threadEventDispatcher
appears to be NULL.
QThread *thread = new QThread;
thread->start();
auto* threadEventDispatcher = thread->eventDispatcher();
Q_ASSERT(threadEventDispatcher != nullptr);
QMetaObject::invokeMethod(threadEventDispatcher, [] { printf("Hello world\n");
According to Qt doc,
An event dispatcher is automatically created for the main thread when QCoreApplication is instantiated and on start() for auxiliary threads.
By browsing the QThread source code, I'm under the impression that the eventDispatcher
is created in the running thread, which may not yet be ready when start
exits.
I managed to access the eventDispatcher
by using a sleep after the start
, but I could not find an API that would allow me to properly wait for the thread to actually run.
How can I wait for the thread to actually run, and access eventDispatcher
?
CodePudding user response:
Simply connect to QThread::started()
signal.