Skip to content

Commit

Permalink
Add async option to add_spawn_function
Browse files Browse the repository at this point in the history
Some things may need to be started synchronously (if they're functions
that themselves start an asynchronous loop for instance).
  • Loading branch information
c-mita committed Jun 22, 2016
1 parent 2eb5d3d commit a0458f7
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
3 changes: 2 additions & 1 deletion malcolm/core/servercomms.py
Expand Up @@ -12,7 +12,8 @@ def __init__(self, name, process):
self.q = self.process.create_queue()
self.add_spawn_function(self.send_loop,
self.make_default_stop_func(self.q))
self.add_spawn_function(self.start_recv_loop, self.stop_recv_loop)
self.add_spawn_function(self.start_recv_loop, self.stop_recv_loop,
async=False)

def send_loop(self):
"""Service self.q, sending responses to client"""
Expand Down
13 changes: 8 additions & 5 deletions malcolm/core/spawnable.py
Expand Up @@ -22,14 +22,17 @@ def start(self, process=None):
if process is None:
process = self.process
self._initialize()
for (func, stop_func) in self._spawn_functions:
self._spawned.append(process.spawn(func))
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) in reversed(self._spawn_functions):
for (func, stop_func, async) in reversed(self._spawn_functions):
if stop_func is not None:
stop_func()

Expand All @@ -39,15 +42,15 @@ def wait(self, timeout=None):
spawned.wait(timeout=timeout)
self._spawned = []

def add_spawn_function(self, func, stop_func=None):
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))
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
Expand Down
2 changes: 1 addition & 1 deletion tests/test_core/test_servercomms.py
Expand Up @@ -21,7 +21,7 @@ def test_init(self, def_stop, add_func):
server.q, self.process.create_queue.return_value)
self.assertEquals(
[call(server.send_loop, def_stop.return_value),
call(server.start_recv_loop, server.stop_recv_loop)],
call(server.start_recv_loop, server.stop_recv_loop, async=False)],
server.add_spawn_function.call_args_list)

def test_not_implemented_error(self):
Expand Down

0 comments on commit a0458f7

Please sign in to comment.