author | Fabien Ninoles <fabien@tzone.org> |
Sun, 21 Mar 2010 17:06:53 -0400 | |
changeset 2 | a00ae018daf8 |
parent 1 | ee10f7cde07d |
child 3 | 00b6708d1852 |
permissions | -rwxr-xr-x |
0 | 1 |
#!/usr/bin/env python2.6 |
2 |
import sys |
|
3 |
import logging |
|
4 |
import threading |
|
5 |
import Queue |
|
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
6 |
from threadpool import ThreadPool |
0 | 7 |
|
8 |
## |
|
9 |
# A task, representing a series of linked pairs of callback and error |
|
10 |
# handler Concept is similar to twisted, but you need to put all your |
|
11 |
# callback on the task before giving it to the Scheduler. For this |
|
12 |
# reason, you shouldnt call the callback/errorback method yourself (or |
|
13 |
# at least, don't put it back in the scheduler after that). |
|
14 |
||
15 |
class Task(object): |
|
16 |
||
17 |
@staticmethod |
|
18 |
def DefaultCallback(result): |
|
19 |
return result |
|
20 |
||
21 |
@staticmethod |
|
22 |
def DefaultErrorback(error): |
|
23 |
return error |
|
24 |
||
25 |
def __init__(self, func = None, *args, **kwargs): |
|
26 |
super(Task, self).__init__() |
|
27 |
self.callbacks = [] |
|
28 |
if func: |
|
29 |
def callback(result): |
|
30 |
return func(*args, **kwargs) |
|
31 |
self.AddCallback(callback) |
|
32 |
||
33 |
def AddCallback(self, callback, errorback = None): |
|
34 |
if errorback == None: |
|
35 |
errorback = self.DefaultErrorback |
|
36 |
self.callbacks.append((callback, errorback)) |
|
37 |
# permit chained calls |
|
38 |
return self |
|
39 |
||
40 |
def ChainTask(self, task): |
|
41 |
return self.AddCallback(task.Callback, task.Errorback) |
|
42 |
||
43 |
def Callback(self, result, error = None, traceback = None): |
|
44 |
logging.debug("Handling task %r callbacks", self) |
|
45 |
for cb, eb in self.callbacks: |
|
46 |
try: |
|
47 |
if error: |
|
48 |
error = eb(error) |
|
49 |
else: |
|
50 |
result = cb(result) |
|
51 |
except: |
|
52 |
errtype, error, traceback = sys.exc_info() |
|
53 |
if error: |
|
54 |
raise error, None, traceback |
|
55 |
return result |
|
56 |
||
57 |
## |
|
58 |
# Consume the callbacks with an error. Notes that error will |
|
59 |
# raise if not handled and return value would be a result |
|
60 |
def Errorback(self, error, traceback = None): |
|
61 |
return self.Callback(None, error, traceback) |
|
62 |
||
63 |
class Scheduler(threading.Thread): |
|
64 |
||
65 |
class _SchedulerStop(Exception): |
|
66 |
pass |
|
67 |
||
68 |
def __init__(self, poolSize): |
|
69 |
threading.Thread.__init__(self, name = "Scheduler", target = self.Run) |
|
70 |
self.pool = ThreadPool(poolSize) |
|
71 |
self.tasks = Queue.Queue() |
|
72 |
||
73 |
def ExecuteOne(self, blocking = True): |
|
74 |
logging.debug("Looking for next task...") |
|
75 |
try: |
|
76 |
task = self.tasks.get(blocking) |
|
77 |
except Queue.Empty: |
|
78 |
logging.debug("No task to run") |
|
79 |
return |
|
80 |
return task.Callback(None) |
|
81 |
||
82 |
def Run(self): |
|
83 |
logging.info("Scheduler start") |
|
84 |
while True: |
|
85 |
try: |
|
86 |
self.ExecuteOne() |
|
87 |
except self._SchedulerStop: |
|
88 |
break |
|
89 |
except: |
|
90 |
logging.exception("Unhandled task exception") |
|
91 |
logging.info("Scheduler stop") |
|
92 |
||
93 |
def Start(self): |
|
94 |
self.pool.Start() |
|
95 |
return self.start() |
|
96 |
||
97 |
def Stop(self, now = False): |
|
98 |
self.pool.Stop(now) |
|
99 |
if now: |
|
100 |
self.tasks = Queue.Queue() |
|
101 |
def RaiseSchedulerStop(): |
|
102 |
raise self._SchedulerStop |
|
103 |
self.AddTask(Task(RaiseSchedulerStop)) |
|
104 |
self.join() |
|
105 |
||
106 |
def AddTask(self, task, blocking = True): |
|
107 |
self.tasks.put(task, blocking) |
|
108 |
||
109 |
## |
|
110 |
# A job is a task run in a seperated thread. After the job run, a |
|
111 |
# new Task is add to the scheduler either with a result or an error, |
|
112 |
# so that only the task, not the callbacks, is run in the worker |
|
113 |
# thread. Note the passed task is consumed after this call. |
|
114 |
# A better design would have to allow Task to suspend or |
|
115 |
# resume themself and to run in the thread if it want to, but this will |
|
116 |
# required the callback to know about its Task and the scheduler |
|
117 |
# itself, which solve nothing. |
|
118 |
def AddJob(self, task, func, *args, **kwargs): |
|
119 |
def Job(): |
|
120 |
try: |
|
121 |
result = func(*args, **kwargs) |
|
122 |
def returnResult(): |
|
123 |
return result |
|
124 |
jobTask = Task(returnResult) |
|
125 |
except: |
|
126 |
errtype, error, traceback = sys.exc_info() |
|
127 |
def raiseError(): |
|
128 |
raise error, None, traceback |
|
129 |
jobTask = Task(raiseError) |
|
130 |
jobTask.ChainTask(task) |
|
131 |
self.AddTask(jobTask) |
|
132 |
self.pool.AddJob(Job) |
|
133 |
||
134 |
## |
|
135 |
# This basically allow one callback to run in a seperated thread |
|
136 |
# and then get the result to another deferred callback. Helas, |
|
137 |
# this create two Tasks, one for the caller, one for the |
|
138 |
# callbacks, with only the first one having to be passed to the |
|
139 |
# scheduler. This should be more transparent: a callback which |
|
140 |
# required to be run as a job should simply be mark like it and |
|
141 |
# the current task suspend until the job is finished, then resume. |
|
142 |
def CreateCallbackAsJob(self, src, cb): |
|
143 |
dst = Task() |
|
144 |
def CreateJobCallback(result): |
|
145 |
def Job(): |
|
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
146 |
return cb(result) |
0 | 147 |
self.AddJob(dst, Job) |
148 |
src.AddCallback(CreateJobCallback) |
|
149 |
return dst |
|
150 |
||
151 |
# The global scheduler |
|
152 |
scheduler = None |
|
153 |
||
154 |
def StartScheduler(size): |
|
155 |
global scheduler |
|
156 |
if scheduler: |
|
157 |
StopScheduler() |
|
158 |
scheduler = Scheduler(size) |
|
159 |
scheduler.Start() |
|
160 |
||
161 |
def StopScheduler(now = False): |
|
162 |
global scheduler |
|
163 |
if scheduler: |
|
164 |
scheduler.Stop(now) |
|
165 |
scheduler = None |
|
166 |
||
167 |
if __name__ == '__main__': |
|
168 |
from time import sleep |
|
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
169 |
logging.getLogger().setLevel(logging.INFO) |
0 | 170 |
# This function is a sample and shouldn't know about the scheduler |
171 |
count = 0 |
|
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
172 |
def AsyncCall(name, seconds): |
0 | 173 |
global count |
174 |
count += 1 |
|
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
175 |
def Initialize(name, seconds): |
0 | 176 |
print "Here", name |
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
177 |
return name, seconds |
0 | 178 |
def Blocking(args): |
179 |
name, time = args |
|
180 |
print name, "goes to bed" |
|
181 |
sleep(time) |
|
182 |
print name, ": ZZZ..." |
|
183 |
return name |
|
184 |
def Finalize(name): |
|
185 |
global count |
|
186 |
print name, "wakes up!" |
|
187 |
count -= 1 |
|
188 |
||
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
189 |
dinit = Task(Initialize, name, seconds) |
0 | 190 |
# How can I remove the scheduler from the picture ? |
191 |
# The only way I can see is to have a special kind of Task |
|
192 |
# and a suspended queue... May be this will also be more clean |
|
193 |
dfinal = scheduler.CreateCallbackAsJob(dinit, Blocking) |
|
194 |
dfinal.AddCallback(Finalize) |
|
195 |
# This is confusing but the reason is that the dfinal callback |
|
196 |
# will be added to the scheduler by the job itself at the end of |
|
197 |
# its execution. |
|
198 |
return dinit |
|
199 |
||
200 |
logging.info("Starting scheduler with 10 workers") |
|
201 |
StartScheduler(10) |
|
202 |
logging.info("Adding asynccall task") |
|
2
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
203 |
for x in xrange(int(sys.argv[1])): |
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
204 |
dasync = AsyncCall("Toto%d" % (x+1), (x % 10)/10.0) |
a00ae018daf8
Separate thread pool in another file and fix some issues.
Fabien Ninoles <fabien@tzone.org>
parents:
1
diff
changeset
|
205 |
scheduler.AddTask(dasync) |
0 | 206 |
while count > 0: |
207 |
logging.debug("Count = %d", count) |
|
208 |
sleep(1) |
|
209 |
logging.info("Stopping scheduler") |
|
210 |
StopScheduler() |
|
211 |
logging.info("The End.") |