Python - 线程生命周期



线程对象在其生命周期中会经历不同的阶段。创建新的 thread 对象时,必须启动它,这将调用 thread 类的 run() 方法。此方法包含新线程要执行的进程的逻辑。线程在 run() 方法结束时完成其任务,并且新创建的线程与主线程合并。

当线程正在运行时,它可以暂停预定义的持续时间,也可以要求它暂停直到发生特定事件。线程在指定的时间间隔后恢复或进程结束。

thread_life_cycle

Python 中线程生命周期的状态

以下是 Python 线程生命周期的各个阶段 -

  • 创建线程 − 要在 Python 中创建新线程,通常使用 threading 模块中的 Thread 类。
  • 启动线程 - 创建线程对象后,必须通过调用其 start() 方法来启动该对象。这将启动线程的 activity 并在单独的线程中调用其 run() 方法。
  • 暂停/阻塞状态 - 线程可能由于各种原因而暂停或阻塞,例如等待 I/O 操作完成或等待其他线程执行任务。这通常通过调用其 join() 方法进行管理。这将阻塞调用线程,直到正在加入的线程终止。
  • 同步线程 − 同步可确保线程之间的有序执行和共享资源管理。这可以通过使用同步基元(如锁、信号量或条件变量)来完成。
  • 终止 - 线程在其 run() 方法完成执行(通过完成其任务或遇到异常)时终止。

示例:Python 线程生命周期演示

此示例通过显示线程的创建、启动、执行以及与主线程的同步来演示 Python 中的线程生命周期。


import threading

def func(x):
	 	print('Current Thread Details:', threading.current_thread())
	 	for n in range(x):
	 	 	 print('{} Running'.format(threading.current_thread().name), n)
	 	print('Internal Thread Finished...')

# Create thread objects
t1 = threading.Thread(target=func, args=(2,))
t2 = threading.Thread(target=func, args=(3,))

# Start the threads
print('Thread State: CREATED')
t1.start()
t2.start()

# Wait for threads to complete
t1.join()
t2.join()
print('Threads State: FINISHED')

# Simulate main thread work
for i in range(3):
	 	print('Main Thread Running', i)

print("Main Thread Finished...")

输出

执行上述代码时,它会生成以下输出 -

Thread State: CREATED
Current Thread Details: <Thread(Thread-1 (func), started 140051032258112)>
Thread-1 (func) Running 0
Thread-1 (func) Running 1
Internal Thread Finished...
Current Thread Details: <Thread(Thread-2 (func), started 140051023865408)>
Thread-2 (func) Running 0
Thread-2 (func) Running 1
Thread-2 (func) Running 2
Internal Thread Finished...
Threads State: FINISHED
Main Thread Running 0
Main Thread Running 1
Main Thread Running 2
Main Thread Finished...

示例:使用 Synchronization Primitive

下面是另一个演示 Python 中的线程生命周期的示例,包括创建、启动、运行和终止状态,以及使用信号量的同步。


import threading
import time

# Create a semaphore	
semaphore = threading.Semaphore(2)

def worker():
	 	with semaphore:
	 	 	 print('{} has started working'.format(threading.current_thread().name))
	 	 	 time.sleep(2)
	 	 	 print('{} has finished working'.format(threading.current_thread().name))

# Create a list to keep track of thread objects
threads = []

# Create and start 5 threads
for i in range(5):
	 	t = threading.Thread(target=worker, name='Thread-{}'.format(i+1))
	 	threads.append(t)
	 	print('{} has been created'.format(t.name))
	 	t.start()

# Wait for all threads to complete
for t in threads:
	 	t.join()
	 	print('{} has terminated'.format(t.name))

print('Threads State: All are FINISHED')
print("Main Thread Finished...")

输出

执行上述代码时,它会生成以下输出 -

Thread-1 has been created
Thread-1 has started working
Thread-2 has been created
Thread-2 has started working
Thread-3 has been created
Thread-4 has been created
Thread-5 has been created
Thread-1 has finished working
Thread-2 has finished working
Thread-3 has started working
Thread-1 has terminated
Thread-2 has terminated
Thread-4 has started working
Thread-3 has finished working
Thread-5 has started working
Thread-3 has terminated
Thread-4 has finished working
Thread-4 has terminated
Thread-5 has finished working
Thread-5 has terminated
Threads State: All are FINISHED
Main Thread Finished...