[Tutor] How to stop a specific thread in Python 2.7?

Mats Wichmann mats at wichmann.us
Wed Sep 25 16:26:42 EDT 2024


On 9/25/24 13:57, marc nicole wrote:
> Why i want to kill a thread?
> 
> At first, i want to look for two values through a thread, if i got them 
> before an event happens, that's cool, the thread will end itself and i 
> will use the values in the subsequent code, if not i want to kill the 
> background running function/thread, and relaunch the function of thread 
> (blocking call this time) to get the values and then continue the program.
> 
> The context is robotics:

So to start out, from the documentation:

"currently, there are no priorities, no thread groups, and threads 
cannot be destroyed, stopped, suspended, resumed, or interrupted."

(see the bits just above this heading: 
https://docs.python.org/3.12/library/threading.html#thread-local-data)

So you need to find a way to extend your model to the negative case as 
well, so the thread stops itself even if the ideal case didn't occur.  I 
think one approach is to use Event, as you've already started to think 
about, I'd just change the naming to be more clear:


should_stop = threading.Event()
# then at some point:
should_stop.set()


and in your thread:

while not should_stop.wait(1):
     # do whatever work you can do


I'm guessing you've already been here and this isn't new info.  Maybe 
someone else has more experience...

 From stuff I've heard, robotics folks are making use of async I/O to 
solve these situations, rather than threads.  Unfortunately, Python's 
async is a bit of a pain as it's kind of like a virus: a function that 
calls async routines must itself be async, and so on... it kind of 
spreads throughout your program this way, and can be a lot of work 
unless you built it from scratch as async.





More information about the Tutor mailing list