简体   繁体   English

python:如何取消阻止使用recvfrom的脚本

[英]python: How to unblock a script that uses recvfrom

I'm using a client to connect a socket via UDP in python. 我正在使用客户端通过UDP在python中连接套接字。 I have two threads. 我有两个主题。 After a KeyboardInterrupt, the first thread still is waiting for a connection via recvfrom. 在KeyboardInterrupt之后,第一个线程仍然在等待通过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. 我有一个全局变量,所有线程共享,我在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. 如果您的KeyboardInterrupt杀死了第一个线程,并且在发生这种情况时需要配对线程关闭,那么您应该考虑使用守护程序线程。 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. 如果您希望线程正常停止,请将它们设置为非守护进程并使用合适的信号机制(如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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM