简体   繁体   中英

How to poll zmq and variable?

I have python server that waits for a global flag to be set and exits.

In a few threads, I have code that waits using zmq.Poller for a message. It times out, prints a heartbeat message, then waits on poller for a new message:

def timed_recv(zock, msec=5000.0):
    poller = zmq.Poller()
    poller.register(zock, zmq.POLLIN)
    events = dict(poller.poll(msec))
    data = None
    if events and events.get(zock) == zmq.POLLIN:
        # if a message came in time, read it.
        data = zock.recv()
    return data

So in the above function, I wait for 5 seconds for a message to arrive. If none does, the function returns, the calling loop prints a message and waits for a new message:

while not do_exit():
    timed_recv(zock)
    print "Program still here!"
sys.exit()

do_exit() checks a global flag for exitting.

Now, if the flag is set, there can be a 5 second delay between it being set, and the loop exitting. How, can I poll for both zock input, and for the global flag being set so that the loop exits quickly?

I thought I can add to the poller, a file descriptor that closes upon global flag being set. Does that seem reasonable? It seems kind of hackish.

Is there a better way to wait for global flag and POLLIN on zock?

(We are using zmq version 3.0 on debian.)

thanks.

The easiest way is to drop the use of a flag, and use another 0mq socket to convey a message. The poller can then wait on both 0mq sockets. The message could be just a single byte; it's arrival in the poller is the message, not its content.

In doing that you're heading down the road to Actor Model programming.

It's a whole lot easier if a development sticks to one programming model; mixing stuff up (eg 0mq and POSIX condition variables) is inviting a lot of problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM