The Qt Documentation about terminate() tells:
The thread may or may not be terminated immediately, depending on the operating systems scheduling policies. Use QThread::wait() after terminate() for synchronous termination.
but also:
Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.
Assuming you didn't reimplement QThread::run()
(which is usually not necessary) - or if you actually reimplemented run and called exec()
yourself, the usual way to stop a thread would be:
_thread->quit();
_thread->wait();
The first line tells the thread asynchronously to stop execution which usually means the thread will finish whatever it is currently doing and then return from it's event loop. However, quit()
always instantly returns which is why you need to call wait()
so the main thread is blocked until _thread
was actually ended. After that, you can safely start()
the thread again.
If you really want to get rid of the thread as quickly as possible, you can also call wait()
after terminate()
or at least before you call start()
again