Python 教程

16.2 多线程编程:threading 模块

Python多线程编程教程:threading模块详解

Python 教程

本教程介绍Python中的多线程编程,使用threading模块,涵盖基本概念、用法、示例代码和注意事项,适合初学者快速入门。

推荐工具
PyCharm专业版开发必备

功能强大的Python IDE,提供智能代码补全、代码分析、调试和测试工具,提高Python开发效率。特别适合处理列表等数据结构的开发工作。

了解更多

Python多线程编程:threading模块详解

多线程编程允许程序同时执行多个任务,从而提高效率和响应速度。Python通过threading模块轻松实现多线程编程,适合处理I/O密集型任务。

什么是多线程?

多线程指在一个进程中运行多个线程,每个线程独立执行代码。线程共享进程的资源,但有自己的执行路径。

为什么使用多线程?

  • 提高性能:在多核CPU上并行执行,优化I/O操作(如网络请求、文件读写)。
  • 实现并发:让程序同时处理多个任务,避免阻塞。
  • 应用场景:Web服务器、数据爬虫、GUI应用等。

Python threading模块简介

threading是Python标准库的一部分,提供了创建和管理线程的类和方法。它比底层模块_thread更高级和易用。

threading模块的基本用法

1. 导入模块

import threading

2. 创建线程

有两种方式创建线程:

  • 使用函数:将函数作为目标传递给threading.Thread
  • 使用类:继承threading.Thread类,重写run方法。

3. 启动线程

调用线程对象的start()方法开始执行。

4. 等待线程结束

使用join()方法等待线程完成,确保主程序在子线程结束后继续。

示例代码

示例1:使用函数创建线程

import threading
import time

def print_numbers():
    for i in range(5):
        print(f"数字: {i}")
        time.sleep(1)  # 模拟耗时操作

# 创建线程
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()  # 等待线程结束
print("主线程结束")

示例2:使用类创建线程

import threading

class MyThread(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name
    
    def run(self):
        print(f"线程 {self.name} 正在运行")
        for i in range(3):
            print(f"线程 {self.name}: {i}")

# 创建并启动多个线程
thread1 = MyThread("A")
thread2 = MyThread("B")
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("所有线程完成")

注意事项

1. 全局解释器锁(GIL)

Python有GIL,同一时间只有一个线程执行Python字节码,因此多线程在CPU密集型任务中可能不会提升性能。对于CPU密集型任务,考虑使用多进程(multiprocessing模块)。

2. 线程安全

多个线程访问共享数据时可能导致竞争条件。使用锁(Lock)确保数据安全:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    lock.acquire()  # 获取锁
    counter += 1
    lock.release()  # 释放锁

threads = []
for _ in range(10):
    thread = threading.Thread(target=increment)
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()
print(f"最终计数: {counter}")

3. 其他常用功能

  • threading.current_thread():获取当前线程对象。
  • threading.enumerate():返回所有活动线程列表。
  • threading.Timer:定时器,延迟执行线程。

总结

多线程编程是Python中优化程序性能的强大工具。threading模块提供了简单接口来创建和管理线程,但需注意GIL和线程安全问题。对于I/O密集型任务,多线程非常有效;对于CPU密集型任务,建议探索多进程。

通过本教程,您可以快速上手Python多线程编程,实践示例代码以加深理解。

开发工具推荐
Python开发者工具包

包含虚拟环境管理、代码格式化、依赖管理、测试框架等Python开发全流程工具,提高开发效率。特别适合处理复杂数据结构和算法。

获取工具包