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 2bf707c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
3 changes: 2 additions & 1 deletion malcolm/core/servercomms.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 2bf707c

Please sign in to comment.