【问题标题】:ZeroMQ: Waiting for a message without consuming threadZeroMQ:等待消息而不消耗线程
【发布时间】:2020-09-18 21:36:03
【问题描述】:

我有一些简单的 python 代码等待某个主题的消息。

但是...当运行它时,python 进程会占用 CPU。我知道使用其他语言,例如使用套接字,有一种方法可以在不消耗整个处理能力的情况下等待消息。本质上,线程只是保持停止等待响应。 ZeroMQ 有可能吗?

import zmq
import sys

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)

【问题讨论】:

    标签: python zeromq messaging


    【解决方案1】:

    是的,这是可能的。

    上面的代码不是所声称问题的可重现的 MCVE/MWE 表示。

    首先:代码显式阻塞。使用 .recv() 方法会阻塞,直到任何新的匹配消息到达(如果有的话)。

    这不会使 CPU 过载。它只是一直坐在 SUB 一边等待,直到第一个这样的消息(如果有)到达。

    如果对更好的方案感兴趣,请不要以这种方式使用.recv()-方法,而是使用.poll()-方法检测任何此类POSACK-acknowledgement 并阅读@987654326 @-ed 使用 .recv( zmq.NOBLOCK )-方法的案例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多