Skip to content

Instantly share code, notes, and snippets.

@minrk
Created February 2, 2012 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minrk/1720387 to your computer and use it in GitHub Desktop.
Save minrk/1720387 to your computer and use it in GitHub Desktop.
"""Demonstrate interrupting the main thread,
and cleanly shutting down sockets in other threads via ctx.term()
"""
import zmq
from threading import Thread, current_thread
def blocking_recv():
"""simple thread that will call recv, and block forever since nobody is sending"""
ctx = zmq.Context.instance()
s = ctx.socket(zmq.REP)
s.bind_to_random_port('tcp://127.0.0.1')
# block here
try:
s.recv()
except zmq.ZMQError as e:
print "%s interrupted with: %s" % (current_thread().name, str(e))
finally:
s.close()
# everybody gets the same Context:
ctx = zmq.Context.instance()
# start 5 background threads
threads = []
for i in range(5):
t = Thread(target=blocking_recv)
t.start()
# same call in the main thread:
print "use ^C to interrupt the main thread"
try:
blocking_recv()
except KeyboardInterrupt:
print "\nMain thread interrupted, terminating context"
ctx.term()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment