Imported Upstream version 3.2.2
[debian/gnuradio] / gnuradio-core / src / python / gnuradio / gruimpl / msgq_runner.py
1 #
2 # Copyright 2009 Free Software Foundation, Inc.
3 #
4 # This file is part of GNU Radio
5 #
6 # GNU Radio is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
10 #
11 # GNU Radio is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Radio; see the file COPYING.  If not, write to
18 # the Free Software Foundation, Inc., 51 Franklin Street,
19 # Boston, MA 02110-1301, USA.
20 #
21
22 """
23 Convenience class for dequeuing messages from a gr.msg_queue and
24 invoking a callback.
25
26 Creates a Python thread that does a blocking read on the supplied
27 gr.msg_queue, then invokes callback each time a msg is received.
28
29 If the msg type is not 0, then it is treated as a signal to exit
30 its loop.
31
32 If the callback raises an exception, and the runner was created
33 with 'exit_on_error' equal to True, then the runner will store the
34 exception and exit its loop, otherwise the exception is ignored.
35
36 To get the exception that the callback raised, if any, call
37 exit_error() on the object.
38
39 To manually stop the runner, call stop() on the object.
40
41 To determine if the runner has exited, call exited() on the object.
42 """
43
44 from gnuradio import gr
45 import gnuradio.gr.gr_threading as _threading
46
47 class msgq_runner(_threading.Thread):
48
49     def __init__(self, msgq, callback, exit_on_error=False):
50         _threading.Thread.__init__(self)
51
52         self._msgq = msgq
53         self._callback = callback
54         self._exit_on_error = exit_on_error
55         self._done = False
56         self._exited = False
57         self._exit_error = None
58         self.setDaemon(1)
59         self.start()
60
61     def run(self):
62         while not self._done:
63             msg = self._msgq.delete_head()
64             if msg.type() != 0:
65                 self.stop()
66             else:
67                 try:
68                     self._callback(msg)
69                 except Exception, e:
70                     if self._exit_on_error:
71                         self._exit_error = e
72                         self.stop()
73         self._exited = True
74
75     def stop(self):
76         self._done = True
77
78     def exited(self):
79         return self._exited
80
81     def exit_error(self):
82         return self._exit_error