Python - 线程生命周期



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

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

thread_life_cycle

Python 线程生命周期中的状态

以下是 Python 线程生命周期的阶段:

  • 创建线程 − 要在 Python 中创建新线程,通常使用 threading 模块中的 Thread 类。
  • 启动线程 − 创建线程对象后,必须通过调用其 start() 方法来启动它。这会启动线程的活动并在线程中调用其 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...

示例:使用同步原语

这是另一个示例,演示了 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...
广告