Subscribing only while working
A node that keeps its camera, arm-state and TF subscriptions open while it waits for work pays for every message that arrives, whether or not anything reads it. This page is the convention for what a node may subscribe to while nothing has asked it to work.
Why a message is not free
On the Orin, a Python node with a MultiThreadedExecutor spends roughly
1.5 to 2 ms of CPU on every delivered message before the callback runs. The
executor wakes, rebuilds its wait set, deserializes the message and hands it
to a thread. A callback that only stores the message still pays all of that.
So a single 100 Hz topic costs a Python subscriber 15 to 20% of a core, and
three 15 Hz camera topics plus /tf cost about a third of a core before any
work is done on them.
The convention
A node that has not been asked to do anything subscribes to nothing that arrives faster than about 1 Hz. Sensors, arm state and TF are subscribed when work starts and dropped when it ends.
Give each interface that wraps a stream a start() and a stop(), both
idempotent, and call them from whatever marks the start and end of work:
- An enable service creates the subscriptions on
Trueand destroys them onFalse. - An action creates them when the goal is accepted and destroys them in a
finallyblock, so a cancel or an exception also releases them. - Several overlapping users share a reference count under a lock. The subscriptions come up with the first user and go down with the last.
stop() takes the subscriptions out of the executor before it destroys them,
and clears the cached data so a later reader cannot mistake a stale frame for
a fresh one.
Destroying a subscription is not safe on its own under a
MultiThreadedExecutor. If the executor has already queued a handler for
that subscription, the handler raises InvalidHandle from its take when it
runs, the exception comes out of spin(), and the node dies. The safe order
is: give the subscriptions a callback group that answers can_execute with
False once paused, so they leave the wait set and no new handlers are
created; wait until no handler is in flight for them; then destroy. A
single-threaded node that destroys a subscription from inside its own
callback has no second thread to race and needs none of this.
The same applies to TF. tf2_ros.TransformListener.unregister() destroys its
two subscriptions the unsafe way and offers no way to set their callback
group, so a node that starts and stops TF subscribes to /tf and /tf_static
itself, in the paused group, and feeds the buffer with set_transform.
Plan for the warm-up
Data that used to be waiting in a cache now arrives a moment after start().
The delays are small, but the code has to expect them:
- A camera frame arrives within one camera period, about 70 ms at 15 Hz. A pipeline on a 5 Hz timer sees it before its next tick.
- Arm state arrives within one publish period, 20 ms at 50 Hz. A command
loop that reads the latest joint state treats
Noneas “not yet”, not as “reached”. - TF needs two samples on each side of a stamp before a lookup at that
stamp succeeds, about 80 ms with the arm’s state publisher. A per-frame
lookup that already returns
Noneon failure and retries next frame needs no change. - Transient-local topics (
/tf_static, extrinsics,/robot_description) arrive at once on subscribe and cost nothing afterwards. They can stay subscribed for the life of the node.
A reader of the cache skips the sample when the cache is empty; it does not raise.
Keep a warm start if the first real call has to be fast. A node that loads a
model can run it on a few frames at launch so the first real detection is
not a cold start. It calls start() for that, and stop() right after.
What still costs something
Two things remain after the subscriptions are gone, and both are cheap:
- Timers below about 10 Hz. A 5 Hz processing timer that returns at once when disabled is under 1% of a core.
- Status topics at 1 Hz such as
/arm/status,/diagnostics, and the GUI connection flag.
An idle node that follows this page sits under 2% of a core.
Minimal example
A callback group that can be paused, a teardown helper that waits for the
executor, a stream wrapper with idempotent start() and stop(), and a
detector that brings it up from an enable service:
class PausableCallbackGroup(ReentrantCallbackGroup):
"""Members leave the executor's wait set while the group is paused."""
def __init__(self):
super().__init__()
self.active = True
def can_execute(self, entity):
return self.active and super().can_execute(entity)
def destroy_subscriptions(node, group, subscriptions, timeout_sec=2.0):
"""Pause the group, wait for in-flight handlers, then destroy."""
group.active = False
deadline = time.time() + timeout_sec
while time.time() < deadline and any(
getattr(sub, "_executor_event", False) for sub in subscriptions
):
time.sleep(0.005)
for sub in subscriptions:
node.destroy_subscription(sub)
class CameraStream:
def __init__(self, node, topic):
self._node, self._topic = node, topic
self._group = None
self._sub = None
self.latest = None
def start(self):
if self._sub is not None:
return
self._group = PausableCallbackGroup() # fresh group per start
self._sub = self._node.create_subscription(
Image, self._topic, self._on_image, 1, callback_group=self._group)
def stop(self):
if self._sub is None:
return
destroy_subscriptions(self._node, self._group, [self._sub])
self._sub = self._group = None
self.latest = None # never serve a stale frame after a restart
def _on_image(self, msg):
self.latest = msg
class Detector(Node):
def __init__(self):
super().__init__("detector")
self.camera = CameraStream(self, "/camera/color/image_raw")
self.create_service(SetBool, "~/enable", self._on_enable)
self.create_timer(0.2, self._tick) # 5 Hz, returns at once when idle
def _on_enable(self, request, response):
if request.data:
self.camera.start()
else:
self.camera.stop()
response.success = True
return response
def _tick(self):
frame = self.camera.latest
if frame is None: # disabled, or the first frame is not here yet
return
self.process(frame)When more than one action or service can be running at once, replace the enable handler with a reference count:
def _acquire_sensors(self):
with self._sensor_lock:
self._sensor_users += 1
if self._sensor_users == 1:
self.camera.start()
def _release_sensors(self):
with self._sensor_lock:
self._sensor_users -= 1
if self._sensor_users == 0:
self.camera.stop()What does not belong here
- Throttling inside the callback. Dropping nine messages out of ten in Python still pays the executor cost for all ten. Either the publisher sends less, or the subscriber is not there.
- A subscription kept open so the data is buffered and ready. The buffer costs more than the 70 ms it saves.
- Polling
rclpy.spin_oncefrom a callback to fetch fresh data. It detaches the node from its executor and delivery stops. See Waiting without spinning.
Related
- Publishing at the rate of the data — the same rule from the publisher’s side.