Python运行eventlet时CPU占用99%
我已经在python和eventlet的邮件列表上发过帖子了,所以如果我显得有点不耐烦,我先说声抱歉。
我在一个小型(不是微型)保留的ubuntu 11.10 aws实例上运行eventlet 0.9.16。
我有一个socket服务器,和eventlet文档中的回声服务器示例很相似。当我第一次运行代码时,一切看起来都很好,但我注意到在运行了10到15个小时后,CPU的使用率从大约1%飙升到99%以上。到那时,我就无法再连接到这个socket服务器了。
这是我正在运行的代码:
def socket_listener(self, port, socket_type):
L.LOGG(self._CONN, 0, H.func(), 'Action:Starting|SocketType:%s' % socket_type)
listener = eventlet.listen((self._host, port))
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
pool = eventlet.GreenPool(20000)
while True:
connection, address = listener.accept()
connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
L.LOGG(self._CONN, 0, H.func(), 'IPAddress:%s|GreenthreadsFree:%s|GreenthreadsRunning:%s' % (str(address[0]), str(pool.free()),str(pool.running())))
pool.spawn_n(self.spawn_socketobject, connection, address, socket_type)
listener.shutdown(socket.SHUT_RDWR)
listener.close()
L.LOGG方法只是把提供的参数记录到一个mysql表中。
我像这样在一个线程中运行socket_listener:
def listen_phones(self):
self.socket_listener(self._port_phone, 'phone')
t_phones = Thread(target = self.listen_phones)
t_phones.start()
根据我最初的谷歌搜索,我认为这个问题可能和在https://lists.secondlife.com/pipermail/eventletdev/2008-October/000140.html上报告的bug类似,但我使用的是eventlet的新版本,所以这肯定不是问题吧?
2 个回答
1
抱歉回复晚了。
没有像 listener.setblocking(0)
这样的代码,所以它一定是阻塞的,不需要休眠。
另外,请使用像 ps
或 top
这样的工具,至少要确认是哪个 Python 进程占用了所有的 CPU。
如果问题仍然存在,请把它报告到以下任意一个渠道,你可以选择:
- https://bitbucket.org/which_linden/eventlet/issues/new
- https://github.com/eventlet/eventlet/issues/new
- 发邮件到 eventletdev@lists.secondlife.com
2
如果 listener.accept()
是非阻塞的,也就是说它不会一直等待连接,而是会立即返回,你应该让线程稍微休息一下,这样操作系统就可以把工作分配给其他进程。你可以在
time.sleep(0.03)
的末尾加上这个休眠的代码,放在你的 while True
循环的最后面。