我最近读到 BSD kqueue
可以处理各种事件,而不仅仅是文件描述符。但对于 Linux 用户来说,它看起来像这样:
(来自 socketserver python stdlib)
#self being passed to select is a listening socket
try:
while not self.__shutdown_request:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = _eintr_retry(select.select, [self], [], [],
poll_interval)
if self in r:
self._handle_request_noblock()
self.service_actions()
是否有一些聪明的方法来检查 threading.Event()
与 select
或 poll
或者这是一个不可避免的情况必须连接第二个套接字来监听关闭事件?
编辑:我要找的是这样的东西:
select.select([self, clever_wrapper(self.__shutdown_request)], [], [])
最佳答案
Is there some clever way to to check a threading.Event() with select or poll or is it an inevitable situation that one has to connect a second socket to listen for a shutdown event?
我不确定我是否理解正确,但如果您想检测对等点的关闭,您可以简单地通过选择和轮询然后读取来完成。也就是说,如果 select/poll 返回套接字已读取,然后您读取并没有返回任何数据但也没有错误,那么您就知道对等方发出了关闭。
不需要第二个套接字,当然第二个连接甚至无法检测到第一个连接是否已关闭。
关于Python:选择或轮询 threading.event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28131867/