在 Python 中,主线程是在执行 Python 解释器时启动的初始线程。它是 Python 进程中的默认线程,负责管理程序和创建其他线程。每个 Python 程序都至少有一个称为主线程的执行线程。
默认情况下,主线程是非守护程序线程。在本教程中,您将看到有关 Python 编程中主线程的详细说明和相关示例。
访问主线程
Python 中的 threading 模块提供了访问线程的函数。以下是关键功能 -
- threading.current_thread():此函数返回线程。表示当前线程的 Thread 实例。
- threading.main_thread():返回线程。表示主线程的 Thread 实例。
例
threading.current_thread() 函数返回一个线程。表示当前线程的 Thread 实例。下面是一个示例。
它将产生以下输出 -
<_MainThread(MainThread, started 140260292161536)>
例
此示例演示如何使用 threading.main_thread() 函数获取对主线程的引用。它还显示了主线程与使用 threading.current_thread() 函数的其他线程之间的区别。
执行上述代码时,它会产生以下结果 -
Main thread finished
threading.current_thread() not threading.main_thread()
Python 中的主线程行为
每当主线程完成执行脚本中未在单独线程中启动的所有代码时,它就会退出。例如,当您使用 start() 方法启动新线程时,主线程将继续执行脚本中的剩余代码,直到它到达末尾,然后退出。
由于其他线程默认以非守护进程模式启动,因此它们将继续运行,直到完成,即使主线程已退出。
例以下示例显示了 python 多线程程序中的主线程行为。
它将产生以下输出 -
Main Thread Running 0
Internal Thread Running 0
Main Thread Running 1
Main Thread Running 2
Internal Thread Running 1
Main Thread Finished...
Internal Thread Running 2
Internal Thread Running 3
Internal Thread Running 4
Internal Thread Running 5
Internal Thread Finished...
上面的代码可以为不同的运行和不同的编译器生成不同的输出。
主线程等待其他线程
要确保主线程等待所有其他线程完成,您可以使用 join() 方法联接线程。通过使用 join() 方法,您可以控制执行流程,并确保主线程在退出之前正确等待所有其他线程完成其任务。这有助于有效地管理多线程 Python 程序中线程的生命周期。
例此示例演示如何正确管理主线程,并确保它不会在工作线程完成其任务之前退出。
执行上述代码时,它会产生以下结果 -
Worker 2 waiting for Worker 1 to finish
Main thread is still working on task 0
Main thread is still working on task 1
Worker 1 done
Worker 2 started
Main thread is still working on task 2
Main thread is still working on task 3
Worker 2 done
Main thread is still working on task 4
Main thread is still working on task 5
Main thread Completed