Python Forum
Is Event.set() the preferred way to stop a thread?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is Event.set() the preferred way to stop a thread?
#1
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.
Reply
#2
use threadname.stop()
Reply
#3
(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?
Reply
#4
I don't think that's what I said.
See: http://www.xavierdupre.fr/blog/2013-11-02_nojs.html for example
Reply
#5
(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?
Reply
#6
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Anyway to stop a thread and continue it? dimidgen 2 258 Mar-18-2024, 10:53 AM
Last Post: DeaD_EyE
  Error SQLite objects created in a thread can only be used in that same thread. binhduonggttn 3 15,384 Jan-31-2020, 11:08 AM
Last Post: DeaD_EyE
  Preferred way to slice a list SvetlanaofVodianova 3 2,483 Dec-09-2019, 11:50 PM
Last Post: SvetlanaofVodianova
Exclamation Error: There is no current event loop in thread 'MainThread' AlekseyPython 5 15,550 Feb-21-2019, 04:37 AM
Last Post: AlekseyPython
  a preferred choice os the two lines? Skaperen 9 6,244 May-27-2017, 02:31 AM
Last Post: Skaperen
  preferred?: multiple assignment Skaperen 6 6,029 Dec-19-2016, 06:18 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020