How to kill a thread?

Laszlo Nagy gandalf at shopzeus.com
Fri Jun 6 15:54:06 CEST 2008


>
>         def run(self):
>                 while True:
>                         if exit_event.isSet():
>                                 # Thread exiting
>                                 return
>                         try:
>                                 data = q_in.get(timeout = .5)
>                         except Queue.Empty:
>                                 continue
>                         # ... process data
>  
> And then in the MainThread I do exit_event.set() and wait for all 
> threads to exit. It's a pretty awkward solution but works.
>
> BTW Guys, is something like Thread.kill() planned for the future? Or 
> is there a reason not to have it?
Python threads are cooperative. I think there was a discussion about 
this, about a year ago or so. The answer was that in CPython, the 
interpreter has this GIL. Python threads are always running on the same 
processor, but they are not "native". There are operating system 
functions to kill a thread but you must not use them because it can 
crash the interpreter. Python MUST clean up object reference counts, 
manage memory etc. The OS function would kill the thread in a way so 
that it would be impossible to fee up memory, and also the interpreter 
can be left in bad state.

I'm not sure about the details, but the short answer is that it is not 
planned. Many programmers said that you have to write cooperative 
threads anyway. Killing threads forcedly is not a good idea in any language.

I hope others will correct me if I'm wrong.

Best,

   Laszlo




More information about the Python-list mailing list