python多线程示例

⚡ python多线程示例|基础认知与适用场景

在现代计算架构中,python多线程示例虽不适用于CPU密集型任务(受限于GIL),却在IO密集型场景(如网络请求、文件读写、数据库交互)中表现优异。理解其原理与限制,是高效编写并发程序的前提。

《Python并发编程实战》指出:当程序中存在大量等待IO操作时(如爬虫、API调用),多线程可显著缩短总执行时间——因为线程切换开销远低于进程切换,且共享内存空间避免了数据复制开销。

以下对比说明典型场景耗时差异:

任务类型单线程耗时多线程耗时加速比适用性
下载100个网页(各2秒)200秒≈2秒100×✅ 极佳
计算1000万次素数12秒≈12秒1×❌ 无效
读写500个文件(各0.1秒IO)50秒≈5秒10×✅ 优秀

⚠️ 注意:多线程并非“越多越快”。线程过多会导致上下文切换开销激增、内存占用飙升,反而降低性能。实践中推荐线程数 = IO等待时间 / (IO等待时间 + CPU处理时间) × 系统核心数。

〔核心概念〕线程与进程的本质差异

  • 进程:操作系统分配资源的基本单位,拥有独立内存空间,通信需IPC机制(管道、共享内存等)
  • 线程:CPU调度的基本单位,共享所属进程的内存与文件描述符,通信直接高效,但需解决竞态条件
  • 协程:用户态轻量级线程(如asyncio),由程序主动调度,无内核切换开销,适用于海量IO并发

三者关系可表示为:进程 → [线程1, 线程2, ...] → [协程A, 协程B, ...]

〔常见误区〕“Python多线程能利用多核CPU”?

这是最普遍的误解!由于GIL(全局解释器锁)的存在,CPython解释器中同一时刻仅允许一个线程执行Python字节码。即使在多核CPU上,多线程也无法加速CPU密集型任务。

但需澄清:

  1. IO操作期间GIL会被释放 → 多线程可加速IO密集型任务
  2. C扩展模块(如NumPy、OpenCV)可主动释放GIL → 数值计算可真正并行
  3. 多进程可绕过GIL → CPU密集型任务首选multiprocessing

验证实验(Python 3.10):

import time
from threading import Thread
def cpu_bound():
    s = 0
    for i in range(10_000_000):
        s += i * i
    return s
def run_threads(n):
    threads = [Thread(target=cpu_bound) for _ in range(n)]
    start = time.time()
    for t in threads: t.start()
    for t in threads: t.join()
    return time.time() - start
print("1线程:", run_threads(1))
print("4线程:", run_threads(4))

典型输出:1线程: 1.82s, 4线程: 6.73s(4线程反而更慢!)

⚙️ python多线程示例|基础用法与生命周期

〔线程创建〕三种主流方式

  1. 函数式创建(最简方案)
from threading import Thread
import time
def worker(name, delay):
    print(f"线程{name}启动")
    time.sleep(delay)
    print(f"线程{name}完成")
t1 = Thread(target=worker, args=("A", 1))
t2 = Thread(target=worker, args=("B", 2))
t1.start(); t2.start()
t1.join(); t2.join()  # 主线程等待子线程
  1. 继承Thread类(可扩展性强)
class Worker(Thread):
    def __init__(self, name, delay):
        super().__init__()
        self.name = name
        self.delay = delay
    def run(self):
        print(f"线程{self.name}启动")
        time.sleep(self.delay)
        print(f"线程{self.name}完成")
t = Worker("X", 1.5)
t.start()
t.join()
  1. 线程池提交(生产环境推荐)

详见后文concurrent.futures章节。

〔线程状态〕完整生命周期图

Thread实例化后,尚未调用start()
调用start()后,等待CPU分配时间片
获得CPU,执行run()方法
调用sleep()/join()/锁等待时进入
run()方法执行完毕或抛出异常

〔关键操作〕线程控制技巧

  • 设置守护线程:thread.daemon = True → 主线程结束时自动终止子线程
  • 获取线程ID:threading.get_ident()(非系统线程ID)或thread.native_id(Python 3.8+)
  • 线程命名:Thread(name="worker-1") → 便于调试与日志追踪
  • 检测线程存活:thread.is_alive()

⚡ python多线程示例|GIL机制深度解析

〔什么是GIL〕

GIL(Global Interpreter Lock)是CPython解释器的核心设计,确保同一进程内仅一个线程执行Python字节码。其设计初衷是简化内存管理(引用计数+垃圾回收),避免多线程竞争导致的内存损坏。

但GIL带来显著影响:

  • 单进程内无法利用多核CPU并行执行Python代码
  • 线程切换开销固定存在(约100微秒/次)
  • 影响IO密集型任务的线程密度(高并发时)

〔GIL释放时机〕

以下情况会主动释放GIL:

  1. IO操作(如time.sleep()、socket读写、文件I/O)
  2. 执行耗时的C扩展(需C代码主动调用PyEval_ReleaseLock())
  3. 达到执行阈值(Python 3.2+默认每sys.getswitchinterval()秒切换,通常5ms)

验证实验:

import threading, time
def io_task():
    time.sleep(0.1)  # 释放GIL
def cpu_task():
    s = 0
    for _ in range(10_000_000): s += _
    return s
# 测试1:纯IO任务
threads = [threading.Thread(target=io_task) for _ in range(10)]
start = time.time()
for t in threads: t.start()
for t in threads: t.join()
print("10个IO线程耗时:", time.time()-start)  # ≈0.1秒(并行)
# 测试2:纯计算任务
threads = [threading.Thread(target=cpu_task) for _ in range(10)]
start = time.time()
for t in threads: t.start()
for t in threads: t.join()
print("10个CPU线程耗时:", time.time()-start)  # ≈1.8秒(串行)

〔绕过GIL的方案〕

multiprocessing模块

通过创建多个进程绕过GIL限制,每个进程拥有独立GIL,可真正利用多核:

from multiprocessing import Pool
import time
def cpu_bound(n):
    return sum(i*i for i in range(n))
if __name__ == "__main__":
    with Pool(processes=4) as pool:
        start = time.time()
        results = pool.map(cpu_bound, [10_000_000]*4)
        print("多进程耗时:", time.time()-start)

C扩展主动释放GIL

NumPy、Pandas等库在执行耗时计算时会释放GIL,示例:

import numpy as np
import time
def numpy_task():
    # np.dot会释放GIL,真正并行
    a = np.random.rand(1000, 1000)
    b = np.random.rand(1000, 1000)
    return np.dot(a, b)
start = time.time()
threads = [threading.Thread(target=numpy_task) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print("NumPy多线程耗时:", time.time()-start)  # 可能≈0.3秒(并行)

asyncio协程方案

对于高并发IO场景(如10万级网络请求),协程比线程更轻量高效:

import asyncio, aiohttp
async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.text()
async def main():
    urls = ["https://example.com"] * 100
    tasks = [fetch(url) for url in urls]
    results = await asyncio.gather(*tasks)
    print(f"完成{len(results)}个请求")
asyncio.run(main())

🔒 python多线程示例|线程同步与竞态避免

〔竞态条件〕

当多个线程同时读写共享数据时,结果依赖执行顺序,导致不可预测行为:

# 错误示例:计数器竞态
counter = 0
def increment():
    global counter
    for _ in range(100000):
        counter += 1  # 非原子操作!
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print("结果:", counter)  # 通常远小于500000

〔同步原语〕

  1. Lock(互斥锁)
lock = threading.Lock()
counter = 0
def safe_increment():
    global counter
    for _ in range(100000):
        with lock:  # 上下文管理器自动释放
            counter += 1
  1. RLock(可重入锁)

允许同一线程多次获取锁,适用于递归调用:

rlock = threading.RLock()
def recursive_task():
    with rlock:
        if condition:
            recursive_task()  # 不会死锁
  1. Condition(条件变量)

用于线程间协作,如生产者-消费者模型:

condition = threading.Condition()
queue = []
def producer():
    with condition:
        queue.append("item")
        condition.notify()  # 通知等待者
def consumer():
    with condition:
        while not queue:
            condition.wait()  # 阻塞等待
        item = queue.pop(0)
  1. Event(事件)

线程间信号传递,如启动/停止控制:

stop_event = threading.Event()
def worker():
    while not stop_event.is_set():
        do_work()
    print("线程已停止")
# 主线程控制
stop_event.set()  # 触发停止信号
  1. Semaphore(信号量)

控制并发访问资源的线程数量(如数据库连接池):

sem = threading.Semaphore(3)  # 最多3个线程同时访问
def access_db():
    with sem:
        db.query("SELECT ...")

〔死锁预防〕

常见死锁场景:线程A持锁1等锁2,线程B持锁2等锁1

📦 python多线程示例|线程安全队列实战

〔Queue模块〕

queue.Queue是线程安全的FIFO队列,内部已实现锁机制,无需额外同步:

import queue, threading
q = queue.Queue(maxsize=10)
def producer():
    for i in range(100):
        q.put(f"item-{i}")  # 阻塞直到有空间
        print(f"生产: item-{i}")
def consumer():
    while True:
        item = q.get()  # 阻塞直到有数据
        process(item)
        q.task_done()
# 启动消费者(守护线程)
threading.Thread(target=consumer, daemon=True).start()
# 生产者
producer()
# 等待所有任务完成
q.join()

〔三种队列对比〕

Queue(FIFO)

最常用场景:任务分发、工作流处理

LifoQueue(LIFO)

用于回溯算法、撤销操作(如编辑器历史)

PriorityQueue(优先级)

结构:queue.PriorityQueue,元素需实现可比较性

import heapq
pq = queue.PriorityQueue()
pq.put((priority, item))  # priority小者优先

〔实战案例〕线程安全日志系统

import queue, logging, threading
log_queue = queue.Queue()
def logger_thread():
    while True:
        record = log_queue.get()
        if record is None:  # 结束信号
            break
        logger.handle(record)
# 启动日志线程
threading.Thread(target=logger_thread, daemon=True).start()
# 业务线程提交日志
def do_work():
    log_queue.put(logging.LogRecord(...))
    # ... 执行任务
# 主线程结束前发送结束信号
log_queue.put(None)

🚀 python多线程示例|线程池与concurrent.futures

〔ThreadPoolExecutor〕

Python 3.2+推荐的线程管理方式,自动管理线程生命周期:

from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def fetch_url(url):
    # 模拟网络请求
    time.sleep(0.5)
    return f"{url} → {len(url)}字节"
urls = ["https://a.com", "https://b.com", "https://c.com"]
with ThreadPoolExecutor(max_workers=5) as executor:
    # 方式1:map(顺序返回结果)
    results = executor.map(fetch_url, urls)
    # 方式2:submit + as_completed(先完成先处理)
    futures = [executor.submit(fetch_url, url) for url in urls]
    for future in as_completed(futures):
        print(future.result())

〔线程池调优参数〕

max_workers计算公式

min(32, os.cpu_count() + 4)(官方推荐)

更精确方案:IO等待时间 / (IO等待时间 + CPU时间) × 核心数

异常处理

submit返回的Future对象需捕获异常:

future = executor.submit(risky_task)
try:
    result = future.result(timeout=5)  # 超时抛TimeoutError
except Exception as e:
    print(f"任务失败: {e}")

超时控制

所有阻塞操作(如result())应设置timeout:

try:
    result = future.result(timeout=3.0)
except concurrent.futures.TimeoutError:
    print("任务超时,取消中...")
    future.cancel()

〔线程池 vs 进程池〕

场景线程池进程池
IO密集型(爬虫/API)✅ 首选❌ 过度资源
CPU密集型(计算)❌ GIL限制✅ 真并行
内存限制✅ 共享内存❌ 进程复制开销
启动开销✅ 轻量❌ 重

🛠️ python多线程示例|真实项目场景

〔案例1〕多线程下载器(IO密集)

import requests
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
def download_image(url, folder="images"):
    Path(folder).mkdir(exist_ok=True)
    filename = url.split("/")[-1]
    try:
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()
        with open(f"{folder}/{filename}", "wb") as f:
            f.write(resp.content)
        return f"成功: {filename}"
    except Exception as e:
        return f"失败: {filename} → {e}"
urls = [
    "https://picsum.photos/200/300",
    "https://picsum.photos/seed/1/200/300",
    "https://picsum.photos/seed/2/200/300"
]
with ThreadPoolExecutor(max_workers=5) as pool:
    results = list(pool.map(download_image, urls))
    for r in results:
        print(r)

〔案例2〕多线程数据库扫描

import sqlite3
from threading import Thread
def scan_table(table_name, conn):
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM {table_name}")
    rows = cursor.fetchall()
    print(f"{table_name}: {len(rows)}行")
conn = sqlite3.connect("data.db", check_same_thread=False)
tables = ["users", "orders", "products"]
threads = [Thread(target=scan_table, args=(t, conn)) for t in tables]
for t in threads: t.start()
for t in threads: t.join()

〔案例3〕实时监控系统

import threading, time, queue
class Monitor:
    def __init__(self):
        self.alerts = queue.Queue()
        self.running = True
    def cpu_monitor(self):
        while self.running:
            cpu = get_cpu_usage()  # 假设此函数
            if cpu > 90:
                self.alerts.put(f"CPU告警: {cpu}%")
            time.sleep(5)
    def memory_monitor(self):
        while self.running:
            mem = get_memory_usage()
            if mem > 85:
                self.alerts.put(f"内存告警: {mem}%")
            time.sleep(5)
    def run(self):
        threads = [
            threading.Thread(target=self.cpu_monitor),
            threading.Thread(target=self.memory_monitor)
        ]
        for t in threads: t.start()
        # 消费告警
        while self.running:
            try:
                alert = self.alerts.get(timeout=1)
                print(f"[{time.strftime('%H:%M:%S')}] {alert}")
            except queue.Empty:
                continue
monitor = Monitor()
monitor.run()

❓ python多线程示例|网友最关心问题

〔1〕Python多线程和JavaScript单线程+异步模型有何区别?

核心差异在调度机制:

本质:JS是“伪并发”(单线程协作式调度),Python是“真并发”(多线程抢占式调度),但受GIL限制。

〔2〕为什么我的多线程程序比单线程还慢?

常见原因:

  1. CPU密集型任务 → GIL导致串行化
  2. 锁竞争激烈 → 过多线程争抢锁
  3. 线程过多 → 上下文切换开销 > 计算收益
  4. 数据传递开销 → 频繁线程间传大对象

解决方案:用threading.local()减少共享,或改用multiprocessing。

〔3〕如何安全退出多线程程序?

推荐模式:标志位 + join()

import threading, time
stop_flag = False
def worker():
    while not stop_flag:
        do_work()
        time.sleep(0.1)
t = threading.Thread(target=worker)
t.start()
# 主线程控制
time.sleep(5)
stop_flag = True
t.join()  # 确保线程已退出

避免使用threading.Thread.stop()(Python 3.12已移除),因其可能导致资源泄漏。

〔4〕线程池如何实现优雅重启?

分三步:关闭旧池 → 等待完成 → 创建新池

def restart_pool():
    global pool
    # 1. 关闭旧池(拒绝新任务)
    pool.shutdown(wait=False)
    # 2. 等待现有任务完成(带超时)
    time.sleep(2)  # 或用threading.Event同步
    # 3. 创建新池
    pool = ThreadPoolExecutor(max_workers=5)

〔5〕多线程与协程如何选择?

选线程池当:

选协程当: