| 1 |
""" |
| 2 |
The Stackless module allows you to do multitasking without using threads. |
| 3 |
The essential objects are tasklets and channels. |
| 4 |
Please refer to their documentation. |
| 5 |
""" |
| 6 |
|
| 7 |
|
| 8 |
import _continuation |
| 9 |
|
| 10 |
class TaskletExit(Exception): |
| 11 |
pass |
| 12 |
|
| 13 |
CoroutineExit = TaskletExit |
| 14 |
|
| 15 |
|
| 16 |
def _coroutine_getcurrent(): |
| 17 |
"Returns the current coroutine (i.e. the one which called this function)." |
| 18 |
try: |
| 19 |
return _tls.current_coroutine |
| 20 |
except AttributeError: |
| 21 |
|
| 22 |
return _coroutine_getmain() |
| 23 |
|
| 24 |
def _coroutine_getmain(): |
| 25 |
try: |
| 26 |
return _tls.main_coroutine |
| 27 |
except AttributeError: |
| 28 |
|
| 29 |
continulet = _continuation.continulet |
| 30 |
main = coroutine() |
| 31 |
main._frame = continulet.__new__(continulet) |
| 32 |
main._is_started = -1 |
| 33 |
_tls.current_coroutine = _tls.main_coroutine = main |
| 34 |
return _tls.main_coroutine |
| 35 |
|
| 36 |
|
| 37 |
class coroutine(object): |
| 38 |
_is_started = 0 |
| 39 |
|
| 40 |
def __init__(self): |
| 41 |
self._frame = None |
| 42 |
|
| 43 |
def bind(self, func, *argl, **argd): |
| 44 |
"""coro.bind(f, *argl, **argd) -> None. |
| 45 |
binds function f to coro. f will be called with |
| 46 |
arguments *argl, **argd |
| 47 |
""" |
| 48 |
if self.is_alive: |
| 49 |
raise ValueError("cannot bind a bound coroutine") |
| 50 |
def run(c): |
| 51 |
_tls.current_coroutine = self |
| 52 |
self._is_started = 1 |
| 53 |
return func(*argl, **argd) |
| 54 |
self._is_started = 0 |
| 55 |
self._frame = _continuation.continulet(run) |
| 56 |
|
| 57 |
def switch(self): |
| 58 |
"""coro.switch() -> returnvalue |
| 59 |
switches to coroutine coro. If the bound function |
| 60 |
f finishes, the returnvalue is that of f, otherwise |
| 61 |
None is returned |
| 62 |
""" |
| 63 |
current = _coroutine_getcurrent() |
| 64 |
try: |
| 65 |
current._frame.switch(to=self._frame) |
| 66 |
finally: |
| 67 |
_tls.current_coroutine = current |
| 68 |
|
| 69 |
def kill(self): |
| 70 |
"""coro.kill() : kill coroutine coro""" |
| 71 |
current = _coroutine_getcurrent() |
| 72 |
try: |
| 73 |
current._frame.throw(CoroutineExit, to=self._frame) |
| 74 |
finally: |
| 75 |
_tls.current_coroutine = current |
| 76 |
|
| 77 |
@property |
| 78 |
def is_alive(self): |
| 79 |
return self._is_started < 0 or ( |
| 80 |
self._frame is not None and self._frame.is_pending()) |
| 81 |
|
| 82 |
@property |
| 83 |
def is_zombie(self): |
| 84 |
return self._is_started > 0 and not self._frame.is_pending() |
| 85 |
|
| 86 |
getcurrent = staticmethod(_coroutine_getcurrent) |
| 87 |
|
| 88 |
def __reduce__(self): |
| 89 |
if self._is_started < 0: |
| 90 |
return _coroutine_getmain, () |
| 91 |
else: |
| 92 |
return type(self), (), self.__dict__ |
| 93 |
|
| 94 |
|
| 95 |
try: |
| 96 |
from threading import local as _local |
| 97 |
except ImportError: |
| 98 |
class _local(object): |
| 99 |
pass |
| 100 |
|
| 101 |
_tls = _local() |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
from collections import deque |
| 108 |
|
| 109 |
import operator |
| 110 |
__all__ = 'run getcurrent getmain schedule tasklet channel coroutine'.split() |
| 111 |
|
| 112 |
_global_task_id = 0 |
| 113 |
_squeue = None |
| 114 |
_main_tasklet = None |
| 115 |
_main_coroutine = None |
| 116 |
_last_task = None |
| 117 |
_channel_callback = None |
| 118 |
_schedule_callback = None |
| 119 |
|
| 120 |
def _scheduler_remove(value): |
| 121 |
try: |
| 122 |
del _squeue[operator.indexOf(_squeue, value)] |
| 123 |
except ValueError: |
| 124 |
pass |
| 125 |
|
| 126 |
def _scheduler_append(value, normal=True): |
| 127 |
if normal: |
| 128 |
_squeue.append(value) |
| 129 |
else: |
| 130 |
_squeue.rotate(-1) |
| 131 |
_squeue.appendleft(value) |
| 132 |
_squeue.rotate(1) |
| 133 |
|
| 134 |
def _scheduler_contains(value): |
| 135 |
try: |
| 136 |
operator.indexOf(_squeue, value) |
| 137 |
return True |
| 138 |
except ValueError: |
| 139 |
return False |
| 140 |
|
| 141 |
def _scheduler_switch(current, next): |
| 142 |
global _last_task |
| 143 |
prev = _last_task |
| 144 |
if (_schedule_callback is not None and |
| 145 |
prev is not next): |
| 146 |
_schedule_callback(prev, next) |
| 147 |
_last_task = next |
| 148 |
assert not next.blocked |
| 149 |
if next is not current: |
| 150 |
next.switch() |
| 151 |
return current |
| 152 |
|
| 153 |
def set_schedule_callback(callback): |
| 154 |
global _schedule_callback |
| 155 |
_schedule_callback = callback |
| 156 |
|
| 157 |
def set_channel_callback(callback): |
| 158 |
global _channel_callback |
| 159 |
_channel_callback = callback |
| 160 |
|
| 161 |
def getruncount(): |
| 162 |
return len(_squeue) |
| 163 |
|
| 164 |
class bomb(object): |
| 165 |
def __init__(self, exp_type=None, exp_value=None, exp_traceback=None): |
| 166 |
self.type = exp_type |
| 167 |
self.value = exp_value |
| 168 |
self.traceback = exp_traceback |
| 169 |
|
| 170 |
def raise_(self): |
| 171 |
raise self.type(self.value).with_traceback(self.traceback) |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
class channel(object): |
| 177 |
""" |
| 178 |
A channel object is used for communication between tasklets. |
| 179 |
By sending on a channel, a tasklet that is waiting to receive |
| 180 |
is resumed. If there is no waiting receiver, the sender is suspended. |
| 181 |
By receiving from a channel, a tasklet that is waiting to send |
| 182 |
is resumed. If there is no waiting sender, the receiver is suspended. |
| 183 |
|
| 184 |
Attributes: |
| 185 |
|
| 186 |
preference |
| 187 |
---------- |
| 188 |
-1: prefer receiver |
| 189 |
0: don't prefer anything |
| 190 |
1: prefer sender |
| 191 |
|
| 192 |
Pseudocode that shows in what situation a schedule happens: |
| 193 |
|
| 194 |
def send(arg): |
| 195 |
if !receiver: |
| 196 |
schedule() |
| 197 |
elif schedule_all: |
| 198 |
schedule() |
| 199 |
else: |
| 200 |
if (prefer receiver): |
| 201 |
schedule() |
| 202 |
else (don't prefer anything, prefer sender): |
| 203 |
pass |
| 204 |
|
| 205 |
NOW THE INTERESTING STUFF HAPPENS |
| 206 |
|
| 207 |
def receive(): |
| 208 |
if !sender: |
| 209 |
schedule() |
| 210 |
elif schedule_all: |
| 211 |
schedule() |
| 212 |
else: |
| 213 |
if (prefer sender): |
| 214 |
schedule() |
| 215 |
else (don't prefer anything, prefer receiver): |
| 216 |
pass |
| 217 |
|
| 218 |
NOW THE INTERESTING STUFF HAPPENS |
| 219 |
|
| 220 |
schedule_all |
| 221 |
------------ |
| 222 |
True: overwrite preference. This means that the current tasklet always |
| 223 |
schedules before returning from send/receive (it always blocks). |
| 224 |
(see Stackless/module/channelobject.c) |
| 225 |
""" |
| 226 |
|
| 227 |
def __init__(self, label=''): |
| 228 |
self.balance = 0 |
| 229 |
self.closing = False |
| 230 |
self.queue = deque() |
| 231 |
self.label = label |
| 232 |
self.preference = -1 |
| 233 |
self.schedule_all = False |
| 234 |
|
| 235 |
def __str__(self): |
| 236 |
return 'channel[%s](%s,%s)' % (self.label, self.balance, self.queue) |
| 237 |
|
| 238 |
def close(self): |
| 239 |
""" |
| 240 |
channel.close() -- stops the channel from enlarging its queue. |
| 241 |
|
| 242 |
If the channel is not empty, the flag 'closing' becomes true. |
| 243 |
If the channel is empty, the flag 'closed' becomes true. |
| 244 |
""" |
| 245 |
self.closing = True |
| 246 |
|
| 247 |
@property |
| 248 |
def closed(self): |
| 249 |
return self.closing and not self.queue |
| 250 |
|
| 251 |
def open(self): |
| 252 |
""" |
| 253 |
channel.open() -- reopen a channel. See channel.close. |
| 254 |
""" |
| 255 |
self.closing = False |
| 256 |
|
| 257 |
def _channel_action(self, arg, d): |
| 258 |
""" |
| 259 |
d == -1 : receive |
| 260 |
d == 1 : send |
| 261 |
|
| 262 |
the original CStackless has an argument 'stackl' which is not used |
| 263 |
here. |
| 264 |
|
| 265 |
'target' is the peer tasklet to the current one |
| 266 |
""" |
| 267 |
do_schedule=False |
| 268 |
assert abs(d) == 1 |
| 269 |
source = getcurrent() |
| 270 |
source.tempval = arg |
| 271 |
while True: |
| 272 |
if d > 0: |
| 273 |
cando = self.balance < 0 |
| 274 |
dir = d |
| 275 |
else: |
| 276 |
cando = self.balance > 0 |
| 277 |
dir = 0 |
| 278 |
|
| 279 |
if cando and self.queue[0]._tasklet_killed: |
| 280 |
|
| 281 |
|
| 282 |
self.balance += d |
| 283 |
self.queue.popleft() |
| 284 |
else: |
| 285 |
|
| 286 |
break |
| 287 |
|
| 288 |
if _channel_callback is not None: |
| 289 |
_channel_callback(self, source, dir, not cando) |
| 290 |
self.balance += d |
| 291 |
if cando: |
| 292 |
|
| 293 |
target = self.queue.popleft() |
| 294 |
source.tempval, target.tempval = target.tempval, source.tempval |
| 295 |
target.blocked = 0 |
| 296 |
if self.schedule_all: |
| 297 |
|
| 298 |
_scheduler_append(target) |
| 299 |
do_schedule = True |
| 300 |
elif self.preference == -d: |
| 301 |
_scheduler_append(target, False) |
| 302 |
do_schedule = True |
| 303 |
else: |
| 304 |
_scheduler_append(target) |
| 305 |
else: |
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
source.blocked = d |
| 312 |
self.queue.append(source) |
| 313 |
_scheduler_remove(getcurrent()) |
| 314 |
do_schedule = True |
| 315 |
|
| 316 |
if do_schedule: |
| 317 |
schedule() |
| 318 |
|
| 319 |
retval = source.tempval |
| 320 |
if isinstance(retval, bomb): |
| 321 |
retval.raise_() |
| 322 |
return retval |
| 323 |
|
| 324 |
def receive(self): |
| 325 |
""" |
| 326 |
channel.receive() -- receive a value over the channel. |
| 327 |
If no other tasklet is already sending on the channel, |
| 328 |
the receiver will be blocked. Otherwise, the receiver will |
| 329 |
continue immediately, and the sender is put at the end of |
| 330 |
the runnables list. |
| 331 |
The above policy can be changed by setting channel flags. |
| 332 |
""" |
| 333 |
return self._channel_action(None, -1) |
| 334 |
|
| 335 |
def send_exception(self, exp_type, msg): |
| 336 |
self.send(bomb(exp_type, exp_type(msg))) |
| 337 |
|
| 338 |
def send_sequence(self, iterable): |
| 339 |
for item in iterable: |
| 340 |
self.send(item) |
| 341 |
|
| 342 |
def send(self, msg): |
| 343 |
""" |
| 344 |
channel.send(value) -- send a value over the channel. |
| 345 |
If no other tasklet is already receiving on the channel, |
| 346 |
the sender will be blocked. Otherwise, the receiver will |
| 347 |
be activated immediately, and the sender is put at the end of |
| 348 |
the runnables list. |
| 349 |
""" |
| 350 |
return self._channel_action(msg, 1) |
| 351 |
|
| 352 |
|
| 353 |
class tasklet(coroutine): |
| 354 |
""" |
| 355 |
A tasklet object represents a tiny task in a Python thread. |
| 356 |
At program start, there is always one running main tasklet. |
| 357 |
New tasklets can be created with methods from the stackless |
| 358 |
module. |
| 359 |
""" |
| 360 |
tempval = None |
| 361 |
_tasklet_killed = False |
| 362 |
|
| 363 |
def __new__(cls, func=None, label=''): |
| 364 |
res = coroutine.__new__(cls) |
| 365 |
res.label = label |
| 366 |
res._task_id = None |
| 367 |
return res |
| 368 |
|
| 369 |
def __init__(self, func=None, label=''): |
| 370 |
coroutine.__init__(self) |
| 371 |
self._init(func, label) |
| 372 |
|
| 373 |
def _init(self, func=None, label=''): |
| 374 |
global _global_task_id |
| 375 |
self.func = func |
| 376 |
self.alive = False |
| 377 |
self.blocked = False |
| 378 |
self._task_id = _global_task_id |
| 379 |
self.label = label |
| 380 |
_global_task_id += 1 |
| 381 |
|
| 382 |
def __str__(self): |
| 383 |
return '<tasklet[%s, %s]>' % (self.label,self._task_id) |
| 384 |
|
| 385 |
__repr__ = __str__ |
| 386 |
|
| 387 |
def __call__(self, *argl, **argd): |
| 388 |
return self.setup(*argl, **argd) |
| 389 |
|
| 390 |
def bind(self, func): |
| 391 |
""" |
| 392 |
Binding a tasklet to a callable object. |
| 393 |
The callable is usually passed in to the constructor. |
| 394 |
In some cases, it makes sense to be able to re-bind a tasklet, |
| 395 |
after it has been run, in order to keep its identity. |
| 396 |
Note that a tasklet can only be bound when it doesn't have a frame. |
| 397 |
""" |
| 398 |
if not callable(func): |
| 399 |
raise TypeError('tasklet function must be a callable') |
| 400 |
self.func = func |
| 401 |
|
| 402 |
def kill(self): |
| 403 |
""" |
| 404 |
tasklet.kill -- raise a TaskletExit exception for the tasklet. |
| 405 |
Note that this is a regular exception that can be caught. |
| 406 |
The tasklet is immediately activated. |
| 407 |
If the exception passes the toplevel frame of the tasklet, |
| 408 |
the tasklet will silently die. |
| 409 |
""" |
| 410 |
self._tasklet_killed = True |
| 411 |
if not self.is_zombie: |
| 412 |
|
| 413 |
coroutine.kill(self) |
| 414 |
_scheduler_remove(self) |
| 415 |
self.alive = False |
| 416 |
|
| 417 |
def setup(self, *argl, **argd): |
| 418 |
""" |
| 419 |
supply the parameters for the callable |
| 420 |
""" |
| 421 |
if self.func is None: |
| 422 |
raise TypeError('cframe function must be callable') |
| 423 |
func = self.func |
| 424 |
def _func(): |
| 425 |
try: |
| 426 |
try: |
| 427 |
coroutine.switch(back) |
| 428 |
func(*argl, **argd) |
| 429 |
except TaskletExit: |
| 430 |
pass |
| 431 |
finally: |
| 432 |
_scheduler_remove(self) |
| 433 |
self.alive = False |
| 434 |
|
| 435 |
self.func = None |
| 436 |
coroutine.bind(self, _func) |
| 437 |
back = _coroutine_getcurrent() |
| 438 |
coroutine.switch(self) |
| 439 |
self.alive = True |
| 440 |
_scheduler_append(self) |
| 441 |
return self |
| 442 |
|
| 443 |
def run(self): |
| 444 |
self.insert() |
| 445 |
_scheduler_switch(getcurrent(), self) |
| 446 |
|
| 447 |
def insert(self): |
| 448 |
if self.blocked: |
| 449 |
raise RuntimeError("You cannot run a blocked tasklet") |
| 450 |
if not self.alive: |
| 451 |
raise RuntimeError("You cannot run an unbound(dead) tasklet") |
| 452 |
_scheduler_append(self) |
| 453 |
|
| 454 |
def remove(self): |
| 455 |
if self.blocked: |
| 456 |
raise RuntimeError("You cannot remove a blocked tasklet.") |
| 457 |
if self is getcurrent(): |
| 458 |
raise RuntimeError("The current tasklet cannot be removed.") |
| 459 |
|
| 460 |
_scheduler_remove(self) |
| 461 |
|
| 462 |
def getmain(): |
| 463 |
""" |
| 464 |
getmain() -- return the main tasklet. |
| 465 |
""" |
| 466 |
return _main_tasklet |
| 467 |
|
| 468 |
def getcurrent(): |
| 469 |
""" |
| 470 |
getcurrent() -- return the currently executing tasklet. |
| 471 |
""" |
| 472 |
|
| 473 |
curr = coroutine.getcurrent() |
| 474 |
if curr is _main_coroutine: |
| 475 |
return _main_tasklet |
| 476 |
else: |
| 477 |
return curr |
| 478 |
|
| 479 |
_run_calls = [] |
| 480 |
def run(): |
| 481 |
""" |
| 482 |
run_watchdog(timeout) -- run tasklets until they are all |
| 483 |
done, or timeout instructions have passed. Tasklets must |
| 484 |
provide cooperative schedule() calls. |
| 485 |
If the timeout is met, the function returns. |
| 486 |
The calling tasklet is put aside while the tasklets are running. |
| 487 |
It is inserted back after the function stops, right before the |
| 488 |
tasklet that caused a timeout, if any. |
| 489 |
If an exception occours, it will be passed to the main tasklet. |
| 490 |
|
| 491 |
Please note that the 'timeout' feature is not yet implemented |
| 492 |
""" |
| 493 |
curr = getcurrent() |
| 494 |
_run_calls.append(curr) |
| 495 |
_scheduler_remove(curr) |
| 496 |
try: |
| 497 |
schedule() |
| 498 |
assert not _squeue |
| 499 |
finally: |
| 500 |
_scheduler_append(curr) |
| 501 |
|
| 502 |
def schedule_remove(retval=None): |
| 503 |
""" |
| 504 |
schedule(retval=stackless.current) -- switch to the next runnable tasklet. |
| 505 |
The return value for this call is retval, with the current |
| 506 |
tasklet as default. |
| 507 |
schedule_remove(retval=stackless.current) -- ditto, and remove self. |
| 508 |
""" |
| 509 |
_scheduler_remove(getcurrent()) |
| 510 |
r = schedule(retval) |
| 511 |
return r |
| 512 |
|
| 513 |
|
| 514 |
def schedule(retval=None): |
| 515 |
""" |
| 516 |
schedule(retval=stackless.current) -- switch to the next runnable tasklet. |
| 517 |
The return value for this call is retval, with the current |
| 518 |
tasklet as default. |
| 519 |
schedule_remove(retval=stackless.current) -- ditto, and remove self. |
| 520 |
""" |
| 521 |
mtask = getmain() |
| 522 |
curr = getcurrent() |
| 523 |
if retval is None: |
| 524 |
retval = curr |
| 525 |
while True: |
| 526 |
if _squeue: |
| 527 |
if _squeue[0] is curr: |
| 528 |
|
| 529 |
_squeue.rotate(-1) |
| 530 |
|
| 531 |
task = _squeue[0] |
| 532 |
|
| 533 |
elif _run_calls: |
| 534 |
task = _run_calls.pop() |
| 535 |
else: |
| 536 |
raise RuntimeError('No runnable tasklets left.') |
| 537 |
_scheduler_switch(curr, task) |
| 538 |
if curr is _last_task: |
| 539 |
|
| 540 |
return retval |
| 541 |
|
| 542 |
def _init(): |
| 543 |
global _main_tasklet |
| 544 |
global _global_task_id |
| 545 |
global _squeue |
| 546 |
global _last_task |
| 547 |
_global_task_id = 0 |
| 548 |
_main_tasklet = coroutine.getcurrent() |
| 549 |
_main_tasklet.__class__ = tasklet |
| 550 |
_last_task = _main_tasklet |
| 551 |
tasklet._init(_main_tasklet, label='main') |
| 552 |
_squeue = deque() |
| 553 |
_scheduler_append(_main_tasklet) |
| 554 |
|
| 555 |
_init() |