目录

第二十八章:多线程

本章目标

完成本章学习后,你将能够:

创建线程

import threading
import time
 
def worker(name):
    print(f"{name} started")
    time.sleep(2)
    print(f"{name} finished")
 
# 创建线程
thread1 = threading.Thread(target=worker, args=("Thread-1",))
thread2 = threading.Thread(target=worker, args=("Thread-2",))
 
# 启动线程
thread1.start()
thread2.start()
 
# 等待完成
thread1.join()
thread2.join()

线程同步

import threading
 
# 锁
lock = threading.Lock()
counter = 0
 
def increment():
    global counter
    for _ in range(1000):
        with lock:
            counter += 1
 
# 信号量
semaphore = threading.Semaphore(3)  # 最多3个线程同时访问
 
# 事件
event = threading.Event()
event.set()    # 设置事件
event.wait()   # 等待事件
event.clear()  # 清除事件

线程池

from concurrent.futures import ThreadPoolExecutor
import time
 
def task(n):
    time.sleep(1)
    return n * n
 
# 使用线程池
with ThreadPoolExecutor(max_workers=4) as executor:
    # 提交单个任务
    future = executor.submit(task, 5)
    result = future.result()
 
    # 批量执行
    results = executor.map(task, range(10))
    for r in results:
        print(r)

GIL

# Python的GIL(全局解释器锁)意味着
# 同一时刻只有一个线程执行Python字节码
# 多线程适合I/O密集型,不适合CPU密集型
 
# CPU密集型应使用多进程

本章练习

1. 实现多线程下载器 2. 实现生产者消费者模式 3. 实现线程安全的队列

下一章:第二十九章:多进程