Question

QThread::terminate() documentation states that it is discouraged to terminate a thread by calling this function.
In my program, I need to terminate a thread before it finishes execution. The thread is performing some heavy computation and I want the user to have control to stop calculation.
How can I do that instead of calling QThread::terminate()?

Was it helpful?

Solution

Set a flag from outside the thread that is checked by the computation within the thread and stop the calculation if the flag is set.

OTHER TIPS

Using flags is an obvious and the most common way to do the trick, but if you are working on a linux/unix platform I would advise you to use pipes instead. I had the same issue where I used a flag (this makes the code threadunsafe, and bugs arising out of such a flag are hard to trace), then I changed the implementation to use pipes which were an efficient way to do the needful.

If you want, for a linux platform I can show you how to use pipes to terminate a QThread.

You may also have windows equivalent of pipes, which I don't know much about as I haven't done much of programming on Windows platform.

Hope this helps

Best is to use flag + mutex which will make the solution thread safe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top