我有一些简单的 PUB/SUB
使用ZeroMQ库的代码。本质上就是无限等待消息返回。
但是,这样做似乎很忙,因为在等待接收消息的时候,python的CPU使用率急剧提高。
有没有更好的方法?我想象中这就像在socket上调用receive的时候,它不是不停地执行指令,浪费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)
Q : "不忙着等ZeroMQ吗?"
是啊
...
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
#_________________________________________