-
Notifications
You must be signed in to change notification settings - Fork 14
/
spawnable.py
64 lines (54 loc) · 2.08 KB
/
spawnable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Spawnable(object):
"""Mixin for starting and stopping spawned functions.
Functions called by self.start are spawned under a provided process
(or self.process if one is not provdied).
Functions called by self.stop are called synchronously, in reverse order.
"""
# Sentinel object to stop spawned loops
STOP = object()
def _initialize(self):
if not hasattr(self, "_spawn_functions"):
self._spawn_functions = []
if not hasattr(self, "_spawned"):
self._spawned = []
def start(self, process=None):
"""Spawn registered functions
Args:
process: Process to use for spawning (default self.process)
"""
if process is None:
process = self.process
self._initialize()
for (func, stop_func, async) in self._spawn_functions:
spawned = process.spawn(func)
self._spawned.append(spawned)
if not async:
spawned.wait()
def stop(self):
"""Call registered stop functions"""
self._initialize()
for (func, stop_func, async) in reversed(self._spawn_functions):
if stop_func is not None:
stop_func()
def wait(self, timeout=None):
self._initialize()
for spawned in self._spawned:
spawned.wait(timeout=timeout)
self._spawned = []
def add_spawn_function(self, func, stop_func=None, async=True):
"""Register functions to be triggered by self.start and self.stop
Args:
func: function to be spawned
stop_func: function to halt the spawned function (default None)
"""
self._initialize()
self._spawn_functions.append((func, stop_func, async))
def make_default_stop_func(self, q):
"""Convenience function for creating a default stop function that puts
a Spawnable.STOP object onto the provided queue
Args:
q (queue): queue to put the stop sentinel on
"""
def stop_func():
q.put(Spawnable.STOP)
return stop_func