Python socketserver向多个客户端发送数据cpu使用率高

2024-07-04 16:41:53 发布

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

我的代码接受来自多个源的gps数据,并将其聚合并发送回连接到一个线程化单套接字的多个客户端。但是我似乎在用cpu的资源运行。在

如果我添加代码来等待来自客户端的一些数据,cpu的使用就会消失,但是客户端只接受gps信息流,他们不会发送任何信息。在

下面是发送数据正常但运行高CPU的服务器代码

class ThreadedServerRequestHandler(SocketServer.StreamRequestHandler):

    def handle(self):
        global SendData
        global SendNow
        while True:
            SendNow
            for line in SendData:
                self.request.sendall(line)
                SendData = []
                SendNow = False
        return

class ServerThread(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    daemon_threads = True
    allow_reuse_address = True

if __name__ == '__main__':
    import socket
    import threading

    address = TxServer
    server = ServerThread(address, ThreadedServerRequestHandler)

    t = threading.Thread(target=server.serve_forever)
    t.setDaemon(True) # don't hang on exit
    t.start()

如果我把它改为低于cpu停止,但它只输出数据,如果我发送按键。在

^{pr2}$

有没有办法在数据发送之前暂停线程?或者我可以模拟接收到的消息来触发来自主程序的数据突发吗?在


Tags: 数据代码selftrue客户端addresscpu线程
1条回答
网友
1楼 · 发布于 2024-07-04 16:41:53

它使用100%CPU的原因是,当你没有什么可写的时候,你只要尽可能快地旋转,直到有东西要写:

while True:
    SendNow
    for line in SendData:
        self.request.sendall(line)
        SendData = []
        SendNow = False

为了使它不使用100%的CPU,你必须找到一些东西让它等待。在

您的修复程序通过等待接收到的数据来实现这一点,但是由于您通常没有任何数据要接收,所以这不是很有用。(正如你所说,“它只在我发送按键时输出数据”。)

同时:

Is there any way to pause the thread until data is sent?

当然可以。你已经在做了。这就是sendall所做的。但这没用。问题是,一旦你发送了所有的数据,你就会一遍又一遍的循环,直到有更多的数据要发送。在

or can I simulate a received message to trigger a data burst from the main program?

当然,但是你会用什么来触发模拟接收?如果你只是要尽可能快地旋转模拟接收,那将不会有任何帮助。在

我想你想要的是围绕数据的condition variable。像这样:

^{pr2}$

然后,无论您的代码是什么,设置SendData(您没有显示)如下所示:

global SendCondition
global SendData
# ...
new_send_data = <whatever>
with SendCondition:
    SendData.append(new_send_data)
    SendCondition.notify()

相关问题 更多 >

    热门问题