我无法理解 Python 中的线程。我有这个程序:
import _thread, time
def print_loop():
num = 0
while 1:
num = num + 1
print(num)
time.sleep(1)
_thread.start_new_thread(print_loop, ())
time.sleep(10)
我的问题是我是否需要关闭线程 print_loop,因为在我看来主线程结束时两个线程都结束了。这是处理线程的正确方法吗?
最佳答案
首先,除非绝对必要,否则请避免使用低级 API。 threading
模块优于 _thread
。通常在 Python 中,避免任何以下划线开头的内容。
现在,您正在寻找的方法称为 join
。即
import time
from threading import Thread
stop = False
def print_loop():
num = 0
while not stop:
num = num + 1
print(num)
time.sleep(1)
thread = Thread(target=print_loop)
thread.start()
time.sleep(10)
stop = True
thread.join()
关于python - 如何在 Python 中正确关闭线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26324441/