c++ - Qt queued exit event for worker object in another thread -
myclass object has worker qobject, working in thread:
class myclass { .... private: qthread thread; worker worker; // inherits qobject }; ... worker.movetothread(&thread); now when call thread.exit() worker thread stops instantly. prefer finish pending events, quit.
i have tried "queued exit":
connect(this, signal(signalfinish()), &thread, slot(quit()),qt::queuedconnection); ... void myclass::finish() { emit signalfinish(); worker.disconnect(); // not queue more events thread.wait(); } but doesn't work. wait forever...
how stop qthread after it's event loop process pending events?
the thread , myclass instances both live in same thread - main thread:
myclass::myclass() { ... q_assert(this->thread() == thread.thread()); yet events you're queuing worker object go worker thread:
worker.movetothread(&thread); q_assert(worker.thread() == &thread); q_assert(worker.thread() != thread.thread()); the queued connection precisely wrong thing because wait on worker thread, main thread's event loop won't run , won't issue more events thread. quit call never delivered, since it's delivered in main thread, main thread blocked.
instead, take advantage of quit being thread-safe method. call worker thread itself:
// vvvvvvv thread context object call connect(this, &myclass::signalfinish, &worker, [this]{ thread.quit(); }); // `quit()` execute in `worker.thread()` note thread context object object thread() call executed in. should not qthread instance, in cases!
when signalfinish emitted, qmetacallevent carrying functor above queued in worker thread's queue, , executed after existing call (and other) events processed first.
since you're calling finish in main thread, don't want wait on thread since block gui , make application unresponsive.
as seems you're submitting job items worker thread, might better served qtconcurrent::run submits job items thread pool, , thread management you. see this answer complete example. see this answer , that answer related tidbits.
Comments
Post a Comment