Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 24 additions & 20 deletions rclpy/rclpy/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def __init__(self):
self._callbacks = []
self._callbacks_lock = threading.Lock()
self._logging_initialized = False
self.__context = None

@property
def handle(self):
Expand Down Expand Up @@ -65,28 +66,27 @@ def init(self,
raise RuntimeError(
'Domain id ({}) should not be lower than zero.'
.format(domain_id))
try:
if self.__context is not None:
raise RuntimeError
except AttributeError:
self.__context = _rclpy.Context(
args if args is not None else sys.argv,
domain_id if domain_id is not None else _rclpy.RCL_DEFAULT_DOMAIN_ID)
if initialize_logging and not self._logging_initialized:
with g_logging_configure_lock:
g_logging_ref_count += 1
if g_logging_ref_count == 1:
_rclpy.rclpy_logging_configure(self.__context)
self._logging_initialized = True

if self.__context is not None:
raise RuntimeError('Context.init() must only be called once')

self.__context = _rclpy.Context(
args if args is not None else sys.argv,
domain_id if domain_id is not None else _rclpy.RCL_DEFAULT_DOMAIN_ID)
if initialize_logging and not self._logging_initialized:
with g_logging_configure_lock:
g_logging_ref_count += 1
if g_logging_ref_count == 1:
_rclpy.rclpy_logging_configure(self.__context)
self._logging_initialized = True

def ok(self):
"""Check if context hasn't been shut down."""
# imported locally to avoid loading extensions on module import
try:
with self.__context, self._lock:
with self._lock:
if self.__context is None:
return False
with self.__context:
return self.__context.ok()
except AttributeError:
return False

def _call_on_shutdown_callbacks(self):
with self._callbacks_lock:
Expand All @@ -98,15 +98,17 @@ def _call_on_shutdown_callbacks(self):

def shutdown(self):
"""Shutdown this context."""
# imported locally to avoid loading extensions on module import
if self.__context is None:
raise RuntimeError('Context must be initialized before it can be shutdown')
with self.__context, self._lock:
self.__context.shutdown()
self._call_on_shutdown_callbacks()
self._logging_fini()

def try_shutdown(self):
"""Shutdown this context, if not already shutdown."""
# imported locally to avoid loading extensions on module import
if self.__context is None:
return
with self.__context, self._lock:
if self.__context.ok():
self.__context.shutdown()
Expand Down Expand Up @@ -141,5 +143,7 @@ def _logging_fini(self):

def get_domain_id(self):
"""Get domain id of context."""
if self.__context is None:
raise RuntimeError('Context must be initialized before it can have a domain id')
with self.__context, self._lock:
return self.__context.get_domain_id()