1
# Copyright 2006 Joe Wreschnig, Alexandre Passos
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License version 2 as
5
# published by the Free Software Foundation
7
# $Id: copool.py 4330 2008-09-14 03:19:26Z piman $
9
"""Manage a pool of routines using Python iterators."""
16
def __wrap(func, funcid, args, kwargs):
17
for value in func(*args, **kwargs):
22
def add(func, *args, **kwargs):
23
"""Register a routine to run in GObject main loop.
25
func should be a function that returns a Python iterator (e.g.
26
generator) that provides values until it should stop being called.
28
Optional Keyword Arguments:
29
priority -- priority to run at (default PRIORITY_LOW)
30
funcid -- mutex/removal identifier for this function
32
Only one function with the same funcid can be running at once.
33
Starting a new function with the same ID will stop the old one. If
34
no funcid is given, the function itself is used. The funcid must
35
be usable as a hash key.
37
funcid = kwargs.pop("funcid", func)
38
if funcid in __routines or funcid in __paused:
40
priority = kwargs.pop("priority", gobject.PRIORITY_LOW)
41
next = __wrap(func, funcid, args, kwargs).next
42
idle_id = gobject.idle_add(next, priority=priority)
43
__routines[funcid] = (idle_id, next, priority)
44
print_d("Added copool function %r with id %r" % (func, funcid))
47
"""Stop a registered routine."""
48
if funcid in __routines:
49
gobject.source_remove(__routines[funcid][0])
50
del(__routines[funcid])
51
if funcid in __paused:
53
print_d("Removed copool function id %r" % funcid)
56
"""Stop all running routines."""
57
for funcid in __routines.keys():
61
"""Temporarily pause a registered routine."""
62
func = __routines[funcid]
64
__paused[funcid] = func
67
"""Resume a paused routine."""
68
if funcid in __paused:
69
old_idle_id, func, priority = __paused[funcid]
71
idle_id = gobject.idle_add(func, priority=priority)
72
__routines[funcid] = (idle_id, func, priority)
75
"""Force this function to iterate once."""
76
if funcid in __routines:
77
__routines[funcid][1]()
78
elif funcid in __paused:
81
raise ValueError("no pooled routine %r" % funcid)