Created
February 2, 2012 00:29
-
-
Save minrk/1720387 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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