Python Forum
Is Event.set() the preferred way to stop a thread? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Is Event.set() the preferred way to stop a thread? (/thread-11581.html)



Is Event.set() the preferred way to stop a thread? - svetlanarosemond - Jul-17-2018

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.



RE: Is Event.set() the preferred way to stop a thread? - Larz60+ - Jul-17-2018

use threadname.stop()


RE: Is Event.set() the preferred way to stop a thread? - svetlanarosemond - Jul-17-2018

(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?


RE: Is Event.set() the preferred way to stop a thread? - Larz60+ - Jul-17-2018

I don't think that's what I said.
See: http://www.xavierdupre.fr/blog/2013-11-02_nojs.html for example


RE: Is Event.set() the preferred way to stop a thread? - svetlanarosemond - Jul-17-2018

(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?


RE: Is Event.set() the preferred way to stop a thread? - DeaD_EyE - Jul-17-2018

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.