我有一个在线程中运行的函数
def connection_listener(data:Data=data):
logger.info("connection listener thread started")
while not data.quit:
try:
socket, address = data.socket.accept()
client = Client(socket, address)
data.clients.append(client)
logger.info(f"client {client.address} connected")
socket.send("You are connected to the server".encode(encoder))
except Exception as err:
logger.error('listener error: ', err)
logger.info("connection listener thread finished")
listener_thread = threading.Thread(target=connection_listener)
threads.append(listener_thread)
我有标志
data.quit
,当我希望我的线程停止时会设置该标志。当我设置此标志时,我的其他线程会停止,但这个线程不会停止,直到它收到套接字上的连接 - data.socket.accept()
正在阻塞。如果没有任何尝试连接,我如何停止该线程?
Python 3.12
您可以尝试将套接字超时设置为较小的时间,以便接受功能在该时间之后停止。
data.socket.settimeout(1.0)
。