Python - 主线程


每个 Python 程序都至少有一个执行线程,称为主线程。主线程默认是非守护线程。

有时我们可能需要在程序中创建额外的线程才能并发执行代码。

这是创建新线程的语法-

object = threading.Thread(target, daemon)

Thread() 构造函数创建一个新对象。通过调用 start() 方法,新线程开始运行,并自动调用作为目标参数的参数给出的函数,该函数默认为run。第二个参数是“daemon”,默认情况下为 None。

例子

from time import sleep from threading import current_thread from threading import Thread # function to be executed by a new thread def run(): # get the current thread thread = current_thread() # is it a daemon thread? print(f'Daemon thread: {thread.daemon}') # create a new thread thread = Thread(target=run) # start the new thread thread.start() # block for a 0.5 sec sleep(0.5)

它将产生以下输出-

Daemon thread: False

因此,通过以下语句创建一个线程 -

t1=threading.Thread(target=run)

该语句创建一个非守护线程。启动时,它调用 run() 方法。