使用python中的select达到100%使用率的CPU [英] CPU reaching 100% usage with select in python

查看:569
本文介绍了使用python中的select达到100%使用率的CPU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中选择时遇到问题,我有一段代码可以让客户端从服务器接收数据,还可以通过在stdin上读取并在服务器套接字上进行写入来发送数据:

I have a problem with a select in python, I have a piece of code which allow a client to receive data from a server and also send it by reading on stdin and writing on the server socket:

readfds = [s, sys.stdin]
writefds = [s, sys.stdout]
my_level = get_my_level(s)
is_co = True
cmd = ""
while (is_co):
    read, write, exception = select.select(readfds, writefds, [], 1)
    if (not (read or write or exception)):
        print "Timeout"
    else:
        for sock in read:
            if (sock == s):
                cmd = readline(s)
                print cmd
            elif (sock == sys.stdin):
                cmd = sys.stdin.readline()
                s.sendall(cmd)
     if (cmd == "mort"):
        is_co = False

我认为这是因为select是非阻塞的,但是当我将其阻塞时,它是同一回事.您能在我的代码中解释wath是错误的吗?

I think it's because of the select is non-blocking but when I make it block it's the same thing. Can you explain wath is wrong in my code ?

谢谢

推荐答案

大概您可以始终写到sys.stdout,因此select.select应该立即返回以让您知道可以写一些东西.然后,此代码处理可读列表,然后重新进入循环.但是sys.stdout并没有任何变化,因此它仍可写.

Presumably you can always write to sys.stdout so select.select should be returning immediately to let you know you can write to something. This code then processes the readable list, and then re-enters the loop. But nothing has changed with respect to sys.stdout so it continues to be writable.

这将在紧密循环中执行并消耗CPU.

This will execute in a tight loop and burn CPU.

这篇关于使用python中的select达到100%使用率的CPU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆