如何在我的Python应用程序中停止这个正在等待接受套接字连接的线程

问题描述 投票:0回答:1

我有一个在线程中运行的函数

    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

python multithreading python-3.12
1个回答
0
投票

您可以尝试将套接字超时设置为较小的时间,以便接受功能在该时间之后停止。

data.socket.settimeout(1.0)

© www.soinside.com 2019 - 2024. All rights reserved.