Python 简明教程

Python - Thread Life cycle

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

当一个线程正在运行时,它可能会暂停一段时间或可能被要求暂停,直到发生某个事件。指定时间间隔过后或进程结束后,线程就会恢复。

thread life cycle

States of a Thread Life Cycle in Python

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

  1. * Creating a Thread − To create a new thread in Python, you typically use the *Thread 类。

  2. * Starting a Thread *− 一旦创建一个线程对象,就必须通过调用其 start() 方法来启动它。这将启动线程的活动,并在一个单独的线程中调用其 run() 方法。

  3. * Paused/Blocked State *− 线程可能因多种原因而暂停或阻塞,例如等待 I/O 操作完成或等待另一个线程执行任务。这通常是通过调用其 join() 方法来管理的。这会阻塞调用线程,直到要加入的线程终止。

  4. * Synchronizing Threads *− 同步确保线程之间有序执行和共享资源管理。这可以通过使用同步原语(如锁、信号量或条件变量)来实现。

  5. *终止 *− 当一个线程的 run() 方法完成执行时,该线程就终止了,可能是因为它完成了任务,或者遇到了一个异常。

Example: Python Thread Life Cycle Demonstration

此示例通过展示线程创建、启动、执行和与主线程的同步,演示了 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...")

Output

当执行以上代码时,它会生成以下输出 −

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...

Example: Using a 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...")

Output

当执行以上代码时,它会生成以下输出 −

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...