1 __version__ = '030415'
2 __author__ = 'spex66@gmx.net'
3
4
5 import threading
6 import time
7
8 # from Python Cookbook (O'Reilley)
9 # Chapter 6.2 Terminating a thread
10 #
11 # isNotStopped and stop instead of join are slightly differences
12 #
13
14 class BaseService(threading.Thread):
15
16 def __init__(self, name=None):
17 """ constructor, setting initial variables """
18 self._stopevent = threading.Event()
19
20 threading.Thread.__init__(self, name=(name or 'BaseService'))
21
22 def isNotStopped(self):
23 "Test if thread has got an ending event or not"
24 return not self._stopevent.isSet()
25
26
27 def run(self):
28 """ example main control loop
29
30 has to be specialized in subtyping
31 """
32 print "%s starts" % (self.getName(),)
33
34 count = 0
35 _sleepperiod = 1.0
36
37 while self.isNotStopped():
38
39 count += 1
40 print "loop %d" % (count,)
41
42 # seems to wait on a set _stopevent
43 #self._stopevent.wait(_sleepperiod)
44
45 print "%s ends" % (self.getName(),)
46
47 def stop(self, timeout=None):
48 self.join(timeout)
49
50 def join(self, timeout=None):
51 """ Stop the thread. """
52 self._stopevent.set()
53 # Calling baseclass join()
54 threading.Thread.join(self, timeout)
55
56 if __name__ == "__main__":
57 testthread = BaseService()
58 testthread.start()
59
60 time.sleep(10.0)
61
62 testthread.stop()
syntax highlighted by Code2HTML, v. 0.9.1