diff --git a/ipykernel/iostream.py b/ipykernel/iostream.py index b7379c416..5c78e91ee 100644 --- a/ipykernel/iostream.py +++ b/ipykernel/iostream.py @@ -75,6 +75,7 @@ def __init__(self, socket, pipe=False, session=False): self._events: deque[Callable[..., Any]] = deque() self._event_pipes: dict[threading.Thread, Any] = {} self._event_pipe_gc_lock: threading.Lock = threading.Lock() + self._schedule_lock: threading.Lock = threading.Lock() self._event_pipe_gc_seconds: float = 10 self._event_pipe_gc_task: asyncio.Task[Any] | None = None self._setup_event_pipe() @@ -305,9 +306,15 @@ def start(self): def stop(self): """Stop the IOPub thread""" - self._stopped = True if not self.thread.is_alive(): + self._stopped = True return + # Once `_stopped` is set under the lock, no schedule() call is sending on an event pipe, + # and later calls run their function directly instead of queueing it. + with self._schedule_lock: + self._stopped = True + # Handle all queued events before stopping the loop. + self.io_loop.add_callback(self._handle_event, None) self.io_loop.add_callback(self.io_loop.stop) self.thread.join(timeout=30) @@ -316,8 +323,8 @@ def stop(self): msg = "IOPub thread did not terminate in 30 seconds" raise TimeoutError(msg) # close *all* event pipes, created in any thread - # event pipes can only be used from other threads while self.thread.is_alive() - # so after thread.join, this should be safe + # event pipes are only used by schedule() before `_stopped` is set, + # so after thread.join, this is safe for event_pipe in self._event_pipes.values(): event_pipe.close() @@ -338,11 +345,13 @@ def schedule(self, f): If the thread is not running, call immediately. """ if self.thread.is_alive(): - self._events.append(f) - # wake event thread (message content is ignored) - self._event_pipe.send(b"") - else: - f() + with self._schedule_lock: + if not self._stopped: + self._events.append(f) + # wake event thread (message content is ignored) + self._event_pipe.send(b"") + return + f() def send_multipart(self, *args, **kwargs): """send_multipart schedules actual zmq send in my thread.