[英]Main thread in Python
I have a long program with a lot of threads in it. 我有一个很长的程序,里面有很多线程。 I created a sample, short code where you can see exactly what the problem is.
我创建了一个简单的示例代码,您可以在其中确切地了解问题所在。
from threading import Thread, active_count
import time
def func(x):
time.sleep(x)
print(active_count())
print(active_count())
t = Thread(target=func, name="thread", args=(5,))
t.start()
print("main thread finished")
Simply put - I do not understand why the main thread is still active even after the last print statement was executed. 简而言之-我不明白为什么即使执行了最后一条print语句后主线程仍然处于活动状态。
Can please someone explain to me why is that and what is the mechanism behind the main thread vs. other threads? 请问有人可以向我解释为什么,主线程和其他线程的作用机理是什么? thank you
谢谢
You must be used to compiled languages like C, where exiting the main routine kills everything. 您必须习惯于C之类的编译语言,在其中退出主例程会杀死所有内容。
In Python, reaching the end of the main thread doesn't destroy the other threads. 在Python中,到达主线程的末尾不会破坏其他线程。
In fact, you cannot really destroy threads, this must be a collaborative task (ex: setting a flag or sending an event so the thread understand it must quit its loop: in your case, you may want to segment your time.sleep()
and check for a flag in between, so you can return from the thread if needed) 实际上,您无法真正销毁线程,这必须是一项协作任务(例如:设置一个标志或发送一个事件,以便线程理解它必须退出其循环:在您的情况下,您可能希望分段时间
time.sleep()
并检查两者之间的标志,以便您可以根据需要从线程返回)
So when the main thread ends its execution, the python interpreter waits for all threads to finish before exiting. 因此,当主线程结束执行时,python解释器将等待所有线程完成后再退出。
Note that it's much better to materialize this wait using the join
method ( t.start()
). 请注意,最好使用
join
方法( t.start()
)来实现此等待。
To achieve what you want you need to mark your thread as daemon before starting it: 要实现所需的功能,需要在启动线程之前将其标记为守护程序:
t = Thread(...)
t.daemon = True
t.start()
See the docs https://docs.python.org/2/library/threading.html#thread-objects : 请参阅docs https://docs.python.org/2/library/threading.html#thread-objects :
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.
该标志的重要性在于,仅保留守护程序线程时,整个Python程序都会退出。
The main thread is not a daemon, so marking your spawned threads as daemons allows you to exit your program as soon as your main thread ends. 主线程不是守护程序,因此将生成的线程标记为守护程序可让您在主线程结束时立即退出程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.