gpt4 book ai didi

python - 不忙于等待 ZeroMQ?

转载 作者:行者123 更新时间:2023-12-05 07:07:30 26 4
gpt4 key购买 nike

我有一些使用 ZeroMQ 库的简单 PUB/SUB 代码。本质上只是无限等待消息返回。

但是,这似乎是忙等待,因为在等待接收消息时,python 的 CPU 使用率急剧上升。

有更好的方法吗?我想象这就像在调用接收时在套接字上一样,它不会不断地执行指令和浪费 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 : "Non busy waiting for 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
#_________________________________________

关于python - 不忙于等待 ZeroMQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62120945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com