Skip to content

Commit 3f35f73

Browse files
authored
Make rclpy.try_shutdown() behavior to follow rclpy.shutdown() more closely (#868)
Signed-off-by: Ivan Santiago Paunovic <[email protected]>
1 parent f2eb216 commit 3f35f73

File tree

3 files changed

+20
-7
lines changed

3 files changed

+20
-7
lines changed

rclpy/rclpy/__init__.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,13 @@ def get_global_executor() -> 'Executor':
100100
# imported locally to avoid loading extensions on module import
101101
from rclpy.executors import SingleThreadedExecutor
102102
__executor = SingleThreadedExecutor()
103+
context = get_default_context()
104+
105+
def reset_executor():
106+
global __executor
107+
__executor.shutdown()
108+
__executor = None
109+
context.on_shutdown(reset_executor)
103110
return __executor
104111

105112

@@ -116,10 +123,6 @@ def shutdown(*, context: Context = None, uninstall_handlers: Optional[bool] = No
116123
If `True`, signal handlers will be uninstalled.
117124
If not, signal handlers won't be uninstalled.
118125
"""
119-
global __executor
120-
if __executor is not None:
121-
__executor.shutdown()
122-
__executor = None
123126
_shutdown(context=context)
124127
if (
125128
uninstall_handlers or (

rclpy/rclpy/context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def on_shutdown(self, callback: Callable[[], None]):
127127
if ismethod(callback):
128128
self._callbacks.append(weakref.WeakMethod(callback, self._remove_callback))
129129
else:
130-
self._callbacks.append(weakref.ref(callback, self._remove_callback))
130+
self._callbacks.append(callback)
131131

132132
def _logging_fini(self):
133133
# This function must be called with self._lock held.

rclpy/rclpy/utilities.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,19 @@ def shutdown(*, context=None):
6060

6161
def try_shutdown(*, context=None):
6262
"""Shutdown rclpy if not already shutdown."""
63+
global g_context_lock
64+
global g_default_context
6365
if context is None:
64-
context = get_default_context()
65-
return context.try_shutdown()
66+
# Replace the default context with a new one if shutdown was successful
67+
# or if the context was already shutdown.
68+
with g_context_lock:
69+
if g_default_context is None:
70+
g_default_context = Context()
71+
g_default_context.try_shutdown()
72+
if not g_default_context.ok():
73+
g_default_context = None
74+
else:
75+
return context.try_shutdown()
6676

6777

6878
def get_rmw_implementation_identifier():

0 commit comments

Comments
 (0)