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

Mats Wichmann mats at wichmann.us
Wed Sep 25 14:33:40 EDT 2024


On 9/25/24 12:25, Mats Wichmann wrote:
> On 9/25/24 11:24, marc nicole via Tutor wrote:
>> Hello guys,
>>
>> I want to know how to kill a specific running thread (say by its id)
>>
>> for now I run and kill a thread like the following:
>> # start thread
>> thread1 = threading.Thread(target= self.some_func(), args=( ...,), )
>> thread1.start()
>> # kill the thread
>> event_thread1 = threading.Event()
>> event_thread1.set()
>>
>> I know that set() will kill all running threads, but if there was thread2
>> as well and I want to kill only thread1?
> There's no official way - as usual we'll come back with a question 
> (well, I will): Why Would You Want To Do That?   Threads often hold 
> critical-section locks and other important things and killing such a 
> thread will put you in an undefined, possibly unstable state.  That may 
> not be your case... it would be useful if you described a use case that 
> causes you to want to kill an individual thread.  Or are you just curious?
eh, should have added, but sent too soon: it's absolutely fine to set a 
flag so that the thread knows to kill itself - that way things can 
happen cleanly.


More information about the Tutor mailing list