显示页面讨论过去修订反向链接回到顶部 本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。 ====== 第二十八章:多线程 ====== ===== 本章目标 ===== 完成本章学习后,你将能够: * 创建和管理线程 * 理解GIL * 使用线程同步机制 * 掌握线程池 ===== 创建线程 ===== <code python> 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() </code> ===== 线程同步 ===== <code python> 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() # 清除事件 </code> ===== 线程池 ===== <code python> 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) </code> ===== GIL ===== <code python> # Python的GIL(全局解释器锁)意味着 # 同一时刻只有一个线程执行Python字节码 # 多线程适合I/O密集型,不适合CPU密集型 # CPU密集型应使用多进程 </code> ===== 本章练习 ===== 1. 实现多线程下载器 2. 实现生产者消费者模式 3. 实现线程安全的队列 下一章:[[python_course:chapter29|第二十九章:多进程]] 登录 Detach Close 该主题尚不存在 您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。 python/chapter28.txt 最后更改: 2026/04/09 14:38由 张叶安 登录