Skip to content

Instantly share code, notes, and snippets.

@minrk
Created August 13, 2012 18:48
Show Gist options
  • Save minrk/3343165 to your computer and use it in GitHub Desktop.
Save minrk/3343165 to your computer and use it in GitHub Desktop.
Example for waking a poller in another thread by using a PUSH/PULL waker socket pair
"""
Example for waking a poller in another thread by using a PUSH/PULL waker socket pair
"""
import threading
import time
import zmq
ctx = zmq.Context()
# setup the wake machinery
waker_pull = ctx.socket(zmq.PULL)
waker_push = ctx.socket(zmq.PUSH)
waker_pull.bind('inproc://wake')
waker_push.connect('inproc://wake')
def wake():
waker_push.send(b'Wake up, sleepyhead!')
def halt():
waker_push.send(b'die')
def worker(waker):
"""the worker thread"""
rep = ctx.socket(zmq.REP)
rep.bind('tcp://127.0.0.1:5555')
poller = zmq.Poller()
poller.register(waker, zmq.POLLIN)
poller.register(rep, zmq.POLLIN)
while True:
events = dict(poller.poll())
if rep in events:
msg = rep.recv_multipart()
print "REP received %s" % msg
rep.send_multipart(msg)
if waker in events:
print "I'm up!"
msg = waker.recv_multipart()
if msg == [b'die']:
print "halting..."
return
worker_thread = threading.Thread(target=worker, args=(waker_pull,))
worker_thread.start()
# this is our application socket:
req = ctx.socket(zmq.REQ)
req.connect('tcp://127.0.0.1:5555')
time.sleep(1)
print "REQ sending 'hi'"
req.send(b'hi')
print "REQ received %s" % req.recv_multipart()
time.sleep(1)
print "waking poller"
wake()
time.sleep(1)
print "REQ sending 'hi again'"
req.send_multipart([b'hi', b'again'])
print "REQ received %s" % req.recv_multipart()
time.sleep(1)
print "asking poller to halt"
halt()
while worker_thread.is_alive():
print '.',
time.sleep(0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment