Skip to content

Instantly share code, notes, and snippets.

@spenthil
Created July 30, 2012 23:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save spenthil/3211707 to your computer and use it in GitHub Desktop.
Save spenthil/3211707 to your computer and use it in GitHub Desktop.
pyzmq: ioloop in separate thread
import zmq, zmq.eventloop.zmqstream,zmq.eventloop.ioloop
import threading
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
zmq.eventloop.ioloop.install()
# run ioloop in separate thread
def threaded_loop():
while True:
logger.debug("starting IOLoop")
zmq.eventloop.ioloop.IOLoop.instance().start()
t = threading.Thread(target=threaded_loop)
t.daemon = True
t.start()
context = zmq.Context()
# like echo - but better
def exclaim(stream, msg):
stream.send("{}!".format(msg[0].upper()))
address = "tcp://127.0.0.1:20120"
rep = context.socket(zmq.REP)
rep.bind(address)
rep_stream = zmq.eventloop.zmqstream.ZMQStream(rep)
rep_stream.on_recv_stream(exclaim)
# the thread ioloop is wrapped in a `while True` so it
# will immediately start up again - we stop it so it picks up (?) the
# newly added `REP` stream
zmq.eventloop.ioloop.IOLoop.instance().stop()
req = context.socket(zmq.REQ)
logger.debug("connecting")
req.connect(address)
logger.debug("sending")
req.send("steveholt")
logger.debug("receiving")
assert(req.recv() == "STEVEHOLT!")
logger.debug("done")
@spenthil
Copy link
Author

Output from the above:

DEBUG:root:starting IOLoop
DEBUG:root:connecting
DEBUG:root:starting IOLoop
DEBUG:root:sending
DEBUG:root:receiving
DEBUG:root:done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment