qi.Signal API¶
Introduction¶
Signal allows communication between threads. One thread emits events, other threads register callback to the signal, and process the events appropriately.
Warning
In Python services, signals must be created before registering the service on the session.
A type can be specified in the constructor of the signal, otherwise any value is supported.
Warning
disconnect
is a blocking method which will wait for the callback to
finish (except if it’s called from withing the callback). The signal
destruction is also blocking. These two cases may cause deadlocks in your
code, be careful.
Signal lazy enabling¶
Sometimes, mainly for performance reasons, it is useful to only enable some
code if a Signal has at least one subscriber. For example, if you have a
signal humanDetected
, you may want to enable the image processing code only
if there is at least one subscriber to the signal to save CPU cycles.
This can be achieved by passing a callback to the Signal constructor, which receives a boolean as an argument. This function will be called synchronously each time the number of subscribers switches between 0 and 1.
def onConnect(c):
if c:
print "First connection"
else:
print "No more connections"
sig = qi::Signal('m', onConnect)
l1 = sig.connect(mycallback) # calls onConnect(True)
l2 = sig.connect(mycallback) # nothing happens
sig.disconnect(l1) # nothing happens
sig.disconnect(l2) # calls onConnect(False)
Reference¶
-
class
qi.
Signal
¶ -
(*args)
trigger the signal. for example:
s = qi.Signal() s(42) s(42, 43)
-
connect
(callback) → int¶ Parameters: callback – the callback that will be called when the signal is triggered Returns: the connection id of the registered callback. Connect the signal to a callback, the callback will be called each time the signal is triggered. Use the id returned to unregister the callback
-
disconnect
(id) → bool¶ Parameters: id – the connection id returned by connect Returns: true on success Disconnect the callback associated to id.
-
disconnectAll
() → bool¶ Returns: true on success disconnect all callback associated to the signal. This function should be used very carefully. It’s extremely rare that it is needed.
-
Examples¶
import qi
def onSignal(value):
print "signal value:", value
s = qi.Signal()
s.connect(onSignal)
#trigger the signal
s(42)