【问题标题】:Non busy waiting for ZeroMQ?不忙于等待 ZeroMQ?
【发布时间】:2020-05-31 18:46:04
【问题描述】:

我有一些使用 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)

【问题讨论】:

  • 你是说CPU使用率很高吗?我试过你的代码,在我的追逐中,它几乎没有使用 0.5% 的 CPU。

标签: python zeromq


【解决方案1】:

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
    #_________________________________________

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2015-07-04
    • 2015-03-13
    相关资源
    最近更新 更多