pythonmultithreadingpython-3.12

how do I stop this thread in my python app that is waiting to accpet socket connection


I have a function that is run in a thread

    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)

I have the flag data.quit which is set when I want my threads to stop. My other threads stop when I set this flag but this one will not stop until it receives a connection on the socket - data.socket.accept() is blocking. How do I stop this thread if nothing tries to connect?

Python 3.12


Solution

  • You can try setting socket time out to a small time so the accept function stops after that time. data.socket.settimeout(1.0).