Terminateable thread
Laszlo Nagy
gandalf at designaproduct.biz
Thu Jun 8 07:48:31 EDT 2006
I wote a TThread class that is 'soft terminateable'. For example:
class MyProcessor(TThread):
def run(self):
while not self.terminated():
self.process_one_item()
My question is that, do I really need to use events for this? Because of
the GIL, assignments are atomic. Is it okay to use a simple
'_terminated' attribute instead of the Event object (see below)? It
would be much better to use a simple 'mythread.terminated' attribute
instead of 'mythread.terminated()' and 'mythread.terminated=True'
instead of 'mythread.terminate()'.
Please advise.
Laszlo
--------------------------
from thread import *
from threading import *
class TermMixIn(object):
"""Terminateable thread mixin class.
Methods in this class are thread safe and
can be used to implement softly terminateable
threads. This class can also be used to create
a main synchronization object."""
def __init__(self):
"""Create a TermMixIn instance.
Default state is not terminated."""
self._terminated = Event()
def terminated(self):
""" @return: if the thread is terminated."""
return self._terminated.isSet()
def terminate(self):
"""Set the terminate flag. Can be called from any thread."""
self._terminated.set()
def checkterminated(self):
"""Check if the thread was terminated.
This sould be periodically called from the softly terminateable
thread itself.
Will raise a L{TerminatedException} if the thread is terminated."""
if self.terminated():
raise TerminatedException()
class TThread(Thread,TermMixIn):
"""Terminateable thread. See the L{TermMixIn} class for details."""
def __init__(self,group=None, target=None, name=None, args=(),
kwargs={}):
TermMixIn.__init__(self)
Thread.__init__(self,group,target,name,args,kwargs)
More information about the Python-list
mailing list