stackless.py 16 KB

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