简体   繁体   English

如何检查由模块线程(在Python 3 _thread中)构成的线程是否正在运行?

[英]How to check if thread made by module thread (in Python 3 _thread) is running?

Yet the thread module works for me. 但是线程模块对我有用。 How to check if thread made by module thread (in Python 3 _thread) is running? 如何检查由模块线程(在Python 3 _thread中)构成的线程是否正在运行? When the function the thread is doing ends, the thread ends too, or doesn't? 当线程正在执行的函数结束时,线程也结束了吗?

def __init__(self):
    self.thread =None
......
if self.thread==None or not self.thread.isAlive() :
        self.thread = thread.start_new_thread(self.dosomething,())
else:
        tkMessageBox.showwarning("XXXX","There's no need to have more than two threads")

I know there is no function called isAlive() in "thread" module, is there any alternative? 我知道“线程”模块中没有名为isAlive()的函数,还有其他选择吗?

But there isn't any reason why to use "threading" module, is there? 但是没有任何理由使用“线程”模块,是吗?

Unless you really need the low-level capabilities of the internal thread ( _thread module, you really should use the threading module instead. It makes everything easier to use and does come with helpers such as is_alive . 除非您确实需要内部thread_thread模块)的低级功能, _thread您确实应该使用threading模块。它使所有内容都易于使用,并且确实带有诸如is_alive帮助is_alive

Btw. 顺便说一句。 the alternative of restarting a thread like you do in your example code would be to keep it running but have it wait for additional jobs. 像在示例代码中一样重新启动线程的另一种方法是保持线程运行,但让它等待其他作业。 Eg you could have a queue somewhere which keeps track of all jobs you want the thread to do, and the thread keeps working on them until the queue is empty—and then it will not terminate but wait for new jobs to appear. 例如,您可能在某个地方有一个队列,该队列跟踪您希望线程执行的所有作业,并且线程一直在处理它们,直到队列为空为止,然后该队列不会终止,而是等待新的作业出现。 And only at the end of the application, you signalize the thread to stop waiting and terminate it. 仅在应用程序结束时,您才发出信号以通知线程停止等待并终止它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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