I'm using a client to connect a socket via UDP in python. I have two threads. After a KeyboardInterrupt, the first thread still is waiting for a connection via recvfrom.

(...)

udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

(...)

udp.shutdown(socket.SHUT_RDWR) # Does not work
udp.close() # Does not work

I have a global variable that all threads share and I update this value after a KeyboardInterrupt. But the thread don't close.

How can I exit from this thread?

Thanks in advance.

有帮助吗?

解决方案

Some clarification might be needed on your part, but this is what I understand from your question. If your KeyboardInterrupt kills the first thread and you need paired threads to close when this occurs, then you should consider using a daemon thread. This will guarantee the end of these threads once the parent thread finishes. However, as mentioned in the docs:

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

Events are nothing other than signals meant to be utilized between threads. Just like a status flag, you can check whether an event has been 'set' and take proper precautions to handle resources before finishing execution within the thread.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top