如何避免高cpu使用率?

2024-06-12 04:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个单独运行的zmq_forwarder.py,它将消息从应用程序传递到sockJS连接,目前我正在研究flask应用程序如何通过zmq从sockJS接收消息。我正在粘贴我的zmq_forwarder.py的内容。我是ZMQ新手,我不知道为什么每次我运行它,它使用100%的CPU负载。在

import zmq

# Prepare our context and sockets
context = zmq.Context()

receiver_from_server = context.socket(zmq.PULL)
receiver_from_server.bind("tcp://*:5561")

forwarder_to_server = context.socket(zmq.PUSH)
forwarder_to_server.bind("tcp://*:5562")

receiver_from_websocket = context.socket(zmq.PULL)
receiver_from_websocket.bind("tcp://*:5563")

forwarder_to_websocket = context.socket(zmq.PUSH)
forwarder_to_websocket.bind("tcp://*:5564")

# Process messages from both sockets
# We prioritize traffic from the server
while True:

    # forward messages from the server
    while True:
        try:
            message = receiver_from_server.recv(zmq.DONTWAIT)
        except zmq.Again:
            break

        print "Received from server: ", message
        forwarder_to_websocket.send_string(message)

    # forward messages from the websocket
    while True:
        try:
            message = receiver_from_websocket.recv(zmq.DONTWAIT)
        except zmq.Again:
            break

        print "Received from websocket: ", message
        forwarder_to_server.send_string(message)

如你所见,我设置了4个插座。该应用程序连接到端口5561以将数据推送到zmq,端口5562连接到zmq接收数据(尽管im仍在考虑如何实际设置它来监听zmq发送的消息)。另一方面,sockjs从端口5564上的zmq接收数据,并在端口5563上向其发送数据。在

我读过zmq.DONTWAIT使消息接收异步且无阻塞,所以我添加了它。在

有没有办法改进代码,使我不超载的CPU?目标是能够使用zmq在flask应用程序和websocket之间传递消息。在


Tags: to端口from应用程序消息messageserverbind
1条回答
网友
1楼 · 发布于 2024-06-12 04:32:00

您在一个紧密的循环中轮询两个接收器套接字,没有任何阻塞(zmq.DONTWAIT),这将不可避免地耗尽CPU。在

注意,ZMQ中有一些支持轮询单个线程中的多个套接字-请参见this answer。我认为您可以调整poller.poll(millis)中的超时,以便代码只在有大量传入消息时使用大量CPU,否则代码将空闲。在

您的另一个选择是使用ZMQ事件循环,使用回调异步响应传入消息。请参阅有关此主题的PyZMQ documentation,以下“echo”示例从中改编:

# set up the socket, and a stream wrapped around the socket
s = ctx.socket(zmq.REP)
s.bind('tcp://localhost:12345')
stream = ZMQStream(s)

# Define a callback to handle incoming messages
def echo(msg):
    # in this case, just echo the message back again
    stream.send_multipart(msg)

# register the callback
stream.on_recv(echo)

# start the ioloop to start waiting for messages
ioloop.IOLoop.instance().start()

相关问题 更多 >