python thread模块如何实现多线程

Python中多线程通过threading模块实现,常用方式包括:1. 创建Thread实例并启动;2. 继承Thread类重写run方法;3. 使用Lock确保共享数据安全;4. 设置守护线程随主线程结束而退出。

Python 中实现多线程主要通过 threading 模块,而不是旧的 thread 模块(在 Python 3 中已被重命名为 _thread,不推荐直接使用)。threading 模块提供了更高级、更易用的接口来管理多线程任务。

1. 使用 threading.Thread 创建线程

最常见的方式是创建 threading.Thread 类的实例,并指定要执行的函数。

  • target:指定线程要运行的函数
  • args:传递给函数的参数,以元组形式传入
  • start():启动线程
  • join():等待线程执行完成

示例代码:

import threading
import time

def print_numbers(): for i in range(5): time.sleep(1) print(i)

def print_letters(): for letter in 'abcde': time.sleep(1.5) print(letter)

创建线程

t1 = threading.Thread(target=print_numbers) t2 = threading.Thread(target=print_letters)

启动线程

t1.start() t2.start()

等待线程结束

t1.join() t2.join()

2. 继承 threading.Thread 类

可以自定义一个类继承 threading.Thread,并重写 run() 方法。

class MyThread(threading.Thread):
    def run(self):
        print(f"{self.name} 开始")
        time.sleep(2)
        print(f"{self.name} 结束")

使用自定义线程

t = MyThread() t.start() t.join()

3. 线程同步与共享数据安全

多个线程访问共享数据时,可能引发竞争条件。可以使用 Lock 来保证同一时间只有一个线程操作数据。

lock = threading.Lock()
counter = 0

def increment(): global counter for _ in range(100000): lock.acquire() counter += 1 lock.release()

t1 = threading.Thread(target=increment) t2 = threading.Thread(target=increment) t1.start() t2.start() t1.join() t2.join() print(counter) # 正确输出 200000

4. 守护线程(Daemon Thread)

设置 daemon=True 后,主线程结束时,守护线程会自动退出。

def background_task():
    while True:
        print("后台运行...")
        time.sleep(1)

t = threading.Thread(target=background_task, daemon=True) t.start()

time.sleep(3) # 主程序运行3秒后退出 print("主程序结束")

程序退出时,守护线程自动终止

基本上就这些。threading 模块让多线程编程变得简单,但要注意避免共享资源冲突。合理使用锁和守护线程,能写出稳定高效的并发程序。不复杂但容易忽略细节。