MCPcopy Create free account
hub / github.com/ActiveState/code / CmdThread

Class CmdThread

recipes/Python/577505_Command_Threads/recipe-577505.py:6–114  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4from functools import partial
5
6class CmdThread(Thread):
7 def __init__(self):
8 Thread.__init__(self)
9 self._queue = Queue()
10 self._status = 'NORMAL'
11 self._statusLock = Lock()
12 self._possibleStatus = ('NORMAL', 'SLEEPING', 'DONE')
13 self._condition = Condition(self._statusLock)
14 self.daemon = True
15 self.start()
16
17 def run(self):
18 while True:
19 self._condition.acquire()
20 if self._status == 'DONE':
21 self._condition.release()
22 break
23
24 if self._status == 'SLEEPING':
25 self._condition.wait() # this function will release the lock when going to sleep
26 self._condition.release()
27 continue
28 self._condition.release()
29
30 try:
31 task = self._queue.get_nowait()
32 except Empty:
33 self._condition.acquire()
34 self._status = 'SLEEPING'
35 self._condition.wait()
36 # Here, we don't change the status to 'NORMAL' here
37 # The status is supposed to be changed by the waker
38 # Before this command thread wakes up.
39 self._condition.release()
40 continue
41
42 if callable(task):
43 try:
44 print 'perform task.'
45 task()
46 except Exception:
47 self._statusLock.acquire()
48 self._status = 'DONE'
49 self._statusLock.release()
50 raise
51 else:
52 # you can define the task interface here.
53 pass
54
55
56 def addCmd(self, callableObj, *args, **argd):
57 """ non-blocking call.
58 """
59 assert(callable(callableObj))
60
61 self._condition.acquire()
62 if self._status == 'DONE':
63 self._condition.release()

Callers 1

demoFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected