超时后停止阻塞python线程

2024-09-27 23:21:41 发布

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

我遇到了一个很难找到解决方案的问题

我正在运行一个新的python线程,该线程随后被套接字连接(python socketio)阻塞,因为它无限期地等待数据。但我需要在5分钟后关闭此线程。 我试图设置一个计时器,用sys.exit()关闭线程,但我发现这是关闭计时器线程本身

以下是迄今为止的代码:

class LiveMatches(commands.Cog):
    def __init__(self, client):
        self.client = client 

    def connect_to_scorebot(self, id):
        feed = MatchFeed(self.client)
        feed.main(id) # when this function is called, 
# it will block the newly created thread to receive the data with the socket

    def create_thread(self, id):
        # we create the thread and call launch_match that will connect to
        # the scorebot
        new_thread = threading.Thread(target=self.connect_to_scorebot, args=(id,))
        # start the thread
        new_thread.start()

Tags: thetoselfclientidnewdeffeed
1条回答
网友
1楼 · 发布于 2024-09-27 23:21:41

有两种选择:

  1. 您可以在线程中使用的套接字上设置超时,以便它在一段时间后从阻塞中返回
  2. 使用带有超时的^{}轮询套接字以获取数据,定期检查线程是否应该退出

#1的示例:

import threading
import socket
import select

# A server that echos only the first data received from a client
def server():
    s = socket.socket()
    s.bind(('',5000))
    s.listen()
    print('server: running')
    while True:
        c,a = s.accept()
        print('server: client connected')
        with c: # closes client socket when with block exits
            echoed = False
            while True:
                data = c.recv(1024)
                if not data: break
                if not echoed:
                    print('server: responding',data)
                    c.sendall(data)
                    echoed = True
        print('server: client disconnected')

def client():
    s = socket.socket()
    s.connect(('localhost',5000))
    with s: # closes client socket when with block exits
        try:
            s.settimeout(5) # 5-second timeout if no data received.
            print('client: send one')
            s.sendall(b'one')
            print('client: got',s.recv(1024))
            print('client: send two')
            s.sendall(b'two')
            print('client: got',s.recv(1024))  # this will timeout
        except socket.timeout:
            print('client: timed out')

# Start server thread.
# As a daemon, it will exit if main thread and client thread both exit.
threading.Thread(target=server,daemon=True).start()

t = threading.Thread(target=client)
t.start()
t.join() # wait for client thread to exit.
t = threading.Thread(target=client)
t.start()
t.join() # wait for client thread to exit.

输出:

server: running
client: send one
server: client connected
server: responding b'one'
client: got b'one'
client: send two
client: timed out
server: client disconnected
client: send one
server: client connected
server: responding b'one'
client: got b'one'
client: send two
client: timed out

注意:服务器没有打印第二个客户端已断开连接。因为它是一个守护进程线程,所以当主线程和客户端线程都退出时,它被终止,并且没有时间识别超时后断开的客户端。如果您想要更干净的退出行为,请不要使用守护进程线程

相关问题 更多 >

    热门问题