Is there some way to close a specific hanging recv zmq socket from another thread in Python without clobbering other sockets that may be in use? The following code doesn’t seem to exit; replacing the sock.close() with ctx.destroy() causes it to exit, but that would obviously destroy all sockets in the context:
import zmq
import time
import threading as th
ctx = zmq.Context()
sock = ctx.socket(zmq.ROUTER)
sock.bind('tcp://*:6000')
def shutdown():
time.sleep(5)
print 'closing'
sock.close()
t = th.Thread(target=shutdown)
t.start()
try:
sock.recv()
except zmq.ZMQError:
print 'closed'
One possibility is to perform the socket operations within a context manager that shuts down sockets using a signal handler that raises an exception when a signal is detected: