如何在 Python 中正确关闭线程

Tom*_*ner 3 python multithreading

我无法理解 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)
Run Code Online (Sandbox Code Playgroud)

我的问题是我是否需要关闭线程 print_loop,因为在我看来,当主线程结束时,两个线程都结束了。这是处理线程的正确方法吗?

Kru*_*lur 6

首先,除非绝对必要,否则避免使用低级 API。该threading模块优于_thread. 通常在 Python 中,避免任何以下划线开头的内容。

现在,您正在寻找的方法称为join。IE

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()
Run Code Online (Sandbox Code Playgroud)