Python Forum

Full Version: Is Event.set() the preferred way to stop a thread?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I posted this question on SO, but didn't receive an answer.

I came across these two pages (1,2) about cancelling threads.

Question:

Is using a boolean to cancel a thread bad practice? Is the preferred method to use Event.set()?

Is there any disadvantage to using the boolean to cancel?

From the docs:

Quote:Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.
use threadname.stop()
(Jul-17-2018, 01:34 AM)Larz60+ Wrote: [ -> ]use threadname.stop()

So you mean, Event.Set() is the preferred way? Correct?

Could you explain why? Is it because boolean isn't thread safe?
I don't think that's what I said.
See: http://www.xavierdupre.fr/blog/2013-11-02_nojs.html for example
(Jul-17-2018, 01:48 AM)Larz60+ Wrote: [ -> ]I don't think that's what I said. See: http://www.xavierdupre.fr/blog/2013-11-02_nojs.html for example

Okay I understand now what you said, but it is reliable? As stated in the post _stop() might disappear in a future version of Python. Given that the method has an underscore, doesn't it go against the guideline of calling those methods in client code? It's meant to be private, correct?
Yes, you should avoid using the private method in client code.
Using just a Boolean to stop a thread may cause race conditions.

The object Event is threadsafe.