diff options
author | Lars Wirzenius <lars.wirzenius@codethink.co.uk> | 2012-06-22 13:49:42 +0100 |
---|---|---|
committer | Lars Wirzenius <lars.wirzenius@codethink.co.uk> | 2012-06-22 13:49:42 +0100 |
commit | e3131af71eb98692090e89c6e1b598fc5b60ccf0 (patch) | |
tree | c2b8c503228cbf2cb3aba03dc48cad104565087a | |
parent | af434f470aa2afcd8b1ef9a46e863927dd089d0f (diff) | |
download | bgproc-baserock/liw/hack.tar.gz |
Add callback method to get_resultsbaserock/liw/hack
-rw-r--r-- | bgproc.py | 11 | ||||
-rw-r--r-- | bgproc_tests.py | 4 |
2 files changed, 13 insertions, 2 deletions
@@ -80,7 +80,7 @@ class BackgroundProcessing(object): for p in self.processes: p.join() - def get_results(self, block=False, block_all=False): + def get_results(self, block=False, block_all=False, callback=None): '''Return currently available results. If 'block' is True, then wait until there is at least one @@ -89,14 +89,21 @@ class BackgroundProcessing(object): If no results are pending, then return an empty list, even if blocking is requested (because it would be an eternal block). + If ``callback`` is not None, it needs to be a function to be + called instead of blocking for a result. The function must + return when there may be a result ready. The function gets + no arguments passed to it. + ''' if (block or block_all) and self.pending == 0: return [] items = [] - do_block = block or block_all + do_block = (block or block_all) and callback is None while True: + if callback is not None: + callback() try: item = self.results.get(do_block) except Queue.Empty: diff --git a/bgproc_tests.py b/bgproc_tests.py index 669409d..daa639c 100644 --- a/bgproc_tests.py +++ b/bgproc_tests.py @@ -57,3 +57,7 @@ class BackgroundProcessingTests(unittest.TestCase): self.assertEqual(self.bg.pending, 0) self.assertEqual(self.bg.get_results(block_all=True), []) + def test_calls_callback(self): + self.bg.get_results(callback=lambda: setattr(self, 'called', True)) + self.assertTrue(self.called) + |