How to kill a thread?
gandalf at shopzeus.com
Fri Jun 6 15:54:06 CEST 2008
> def run(self):
> while True:
> if exit_event.isSet():
> # Thread exiting
> data = q_in.get(timeout = .5)
> except Queue.Empty:
> # ... 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.
More information about the Python-list