Skip to content

Commit 7ee5ead

Browse files
committed
Executors reuse iterator
1 parent 1a2ce96 commit 7ee5ead

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

rclpy/rclpy/executors.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -385,13 +385,18 @@ class SingleThreadedExecutor(Executor):
385385

386386
def __init__(self):
387387
super().__init__()
388+
self._callback_iter = None
388389

389390
def spin_once(self, timeout_sec=None):
391+
# Reuse the same callback iterator to avoid unecessary calls to rcl_wait
392+
if self._callback_iter is None:
393+
self._callback_iter = self.wait_for_ready_callbacks(timeout_sec=timeout_sec)
390394
try:
391-
handler, entity, node = next(self.wait_for_ready_callbacks(timeout_sec=timeout_sec))
392-
handler()
395+
handler, entity, node = next(self._callback_iter)
393396
except StopIteration:
394-
pass
397+
self._callback_iter = None
398+
else:
399+
handler()
395400

396401

397402
class MultiThreadedExecutor(Executor):
@@ -407,6 +412,7 @@ def __init__(self, num_threads=None):
407412
:type num_threads: int
408413
"""
409414
super().__init__()
415+
self._callback_iter = None
410416
if num_threads is None:
411417
try:
412418
num_threads = multiprocessing.cpu_count()
@@ -415,8 +421,12 @@ def __init__(self, num_threads=None):
415421
self._executor = ThreadPoolExecutor(num_threads)
416422

417423
def spin_once(self, timeout_sec=None):
424+
# Reuse the same callback iterator to avoid unecessary calls to rcl_wait
425+
if self._callback_iter is None:
426+
self._callback_iter = self.wait_for_ready_callbacks(timeout_sec=timeout_sec)
418427
try:
419-
handler, entity, node = next(self.wait_for_ready_callbacks(timeout_sec=timeout_sec))
420-
self._executor.submit(handler)
428+
handler, entity, node = next(self._callback_iter)
421429
except StopIteration:
422-
pass
430+
self._callback_iter = None
431+
else:
432+
self._executor.submit(handler)

0 commit comments

Comments
 (0)