In my Qt Multi-threaded program, moveToThread() & QCoreApplication::postEvent() dose work only msleep(1) is followed
-
I am writing a 2-threaded qt program, one thread is main(gui) thread and the other is network thread.
My problem is that the moveToThread() & QCoreApplication::postEvent() mechanism only works when provided with the following msleep() call.
In my network thread, the following code has a problem,
ServerWindowWrapper wrapper; wrapper.moveToThread(QApplication::instance()->thread()); QEvent* ev = new QEvent(); QCoreApplication::postEvent(&wrapper, ev); //msleep(1);
In this case, my posted event is ignored. However, if i uncommented the last line "//msleep(1)", the program works fine as I expected.
Someone told me that an eventloop mechanism depends on sleep dose mean the software design is wrong.
So, I want to know whether there is a way to remove "msleep()" without changing my program's behaviors.
-
@sinjohr I think this things happen. Working with threads is not always a cool path.
According to the documentation, a QEvent::ThreadChange event is sent to the object just before the thread affinity is changed.
You can try to handle the event.
Another option is using the overloaded method
void QCoreApplication::postEvent(QObject * receiver, QEvent * event, int priority)
and use Qt::LowEventPriority.