优雅地终止Python线程 [英] Gracefully Terminating Python Threads

查看:92
本文介绍了优雅地终止Python线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个UNIX客户端程序,该程序正在侦听套接字,标准输入并从文件描述符读取.我将每个任务分配给一个单独的线程,并使用同步队列和信号灯使它们与主"应用程序成功通信.问题是,当我想关闭这些子线程时,它们都在输入上受阻.而且,线程无法在线程中注册信号处理程序,因为在Python中,仅允许执行的主线程这样做.

I am trying to write a unix client program that is listening to a socket, stdin, and reading from file descriptors. I assign each of these tasks to an individual thread and have them successfully communicating with the "main" application using synchronized queues and a semaphore. The problem is that when I want to shutdown these child threads they are all blocking on input. Also, the threads cannot register signal handlers in the threads because in Python only the main thread of execution is allowed to do so.

有什么建议吗?

推荐答案

没有解决此问题的好方法,尤其是在线程阻塞时.

There is no good way to work around this, especially when the thread is blocking.

我遇到了类似的问题( Python:如何终止阻塞线程),而我能够停止线程的唯一方法是关闭基础连接.这导致线程被阻塞以引发和异常,然后允许我检查停止标志并关闭.

I had a similar issue ( Python: How to terminate a blocking thread) and the only way I was able to stop my threads was to close the underlying connection. Which resulted in the thread that was blocking to raise and exception and then allowed me to check the stop flag and close.

示例代码:

class Example(object):
   def __init__(self):
       self.stop = threading.Event()
       self.connection = Connection()
       self.mythread = Thread(target=self.dowork)
       self.mythread.start()     
   def dowork(self):

        while(not self.stop.is_set()):
             try:
                  blockingcall()        
             except CommunicationException:
                  pass
   def terminate():
       self.stop.set()
       self.connection.close()
       self.mythread.join()


要注意的另一件事是通常阻塞操作通常会导致超时.如果您有该选项,我会考虑使用它.我的最后一句话是,您可以随时将线程设置为重音,


Another thing to note is commonly blocking operations generally offer up a timeout. If you have that option I would consider using it. My last comment is that you could always set the thread to deamonic,

来自pydoc:

可以将一个线程标记为守护程序线程".该标志的重要性在于,仅保留守护程序线程时,整个Python程序都会退出.初始值是从创建线程继承的.可以通过daemon属性设置该标志.

A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

这篇关于优雅地终止Python线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆