Non busy waiting for ZeroMQ?

Viewed 173

I have some simple PUB/SUB code using the ZeroMQ library. Essentially just waiting infinitely for messages to be returned.

However, this seems to be busy waiting as while waiting to receive a message, pythons CPU usage raises dramatically.

Is there a better way to do this? I imagined this would be like on a socket when you call receive, it isn't constantly executing instructions and wasting CPU.

import sys
import zmq

port = "5556"
if len(sys.argv) > 1:
    port =  sys.argv[1]
    int(port)

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)

print "Collecting updates from weather server..."
socket.connect ("tcp://localhost:%s" % port)

# Subscribe to zipcode, default is NYC, 10001
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

# Process 5 updates
total_value = 0
for update_nbr in range (5):
    string = socket.recv()
    topic, messagedata = string.split()
    total_value += int(messagedata)
    print ('{} {}'.format(topic, message)
1 Answers

Q : "Non busy waiting for ZeroMQ?"

Sure.

...
for update_nbr in range( 5 ):
    print "{0:} A hunt for message started".format( time.ctime() )
    while True: # .............................................. poll() + wait
          if ( 0 == socket.poll( 1000 ) ):
               print "\n.",
          else:
               break # we've got a message .....................
    print "\n{0:} A message came".format( time.ctime() )
    #_________________________________________
    try:
        string = socket.recv( zmq.NOBLOCK )
        topic, messagedata = string.split()
        total_value += int( messagedata )
        print '{} {}'.format( topic, message )

    except:
        print 'EXC:...'

    finally:
        pass
    #_________________________________________
Related