Skip to content

Commit e3ac7a6

Browse files
minrkccordoba12blink1073
authored
ThreadedZMQStream: close stream before socket (#936)
Co-authored-by: Carlos Cordoba <[email protected]> Co-authored-by: Steven Silvester <[email protected]>
1 parent f6a03ac commit e3ac7a6

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

jupyter_client/threaded.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
import asyncio
55
import atexit
66
import time
7+
from concurrent.futures import Future
78
from threading import Event, Thread
89
from typing import Any, Dict, List, Optional
910

1011
import zmq
1112
from tornado.ioloop import IOLoop
1213
from traitlets import Instance, Type
14+
from traitlets.log import get_logger
1315
from zmq.eventloop import zmqstream
1416

1517
from .channels import HBChannel
@@ -45,7 +47,7 @@ def __init__(
4547
session : :class:`session.Session`
4648
The session to use.
4749
loop
48-
A pyzmq ioloop to connect the socket to using a ZMQStream
50+
A tornado ioloop to connect the socket to using a ZMQStream
4951
"""
5052
super().__init__()
5153

@@ -79,7 +81,30 @@ def stop(self) -> None:
7981
self._is_alive = False
8082

8183
def close(self) -> None:
82-
""" "Close the channel."""
84+
"""Close the channel."""
85+
if self.stream is not None and self.ioloop is not None:
86+
# c.f.Future for threadsafe results
87+
f: Future = Future()
88+
89+
def close_stream():
90+
try:
91+
if self.stream is not None:
92+
self.stream.close(linger=0)
93+
self.stream = None
94+
except Exception as e:
95+
f.set_exception(e)
96+
else:
97+
f.set_result(None)
98+
99+
self.ioloop.add_callback(close_stream)
100+
# wait for result
101+
try:
102+
f.result(timeout=5)
103+
except Exception as e:
104+
log = get_logger()
105+
msg = f"Error closing stream {self.stream}: {e}"
106+
log.warning(msg, RuntimeWarning, stacklevel=2)
107+
83108
if self.socket is not None:
84109
try:
85110
self.socket.close(linger=0)

0 commit comments

Comments
 (0)