Python进阶教程:多线程与多进程 目录Python进阶教程多线程与多进程一、为什么需要并发二、多线程threading2.1 创建线程的两种方式2.2 多线程加速 I/O 任务三、线程安全与锁四、线程池ThreadPoolExecutor五、多进程multiprocessing六、进程池ProcessPoolExecutor七、如何选择线程还是进程八、实战并发下载器总结Python进阶教程多线程与多进程本文是Python 入门教程系列的第 6 篇。前面介绍了网络编程与数据抓取本篇讲解 Python 并发编程的核心多线程与多进程。一、为什么需要并发当程序有大量 I/O 操作网络请求、文件读写或计算密集任务时串行执行会浪费大量等待时间。并发编程能让多个任务同时推进大幅提升效率。二、多线程threading2.1 创建线程的两种方式importthreadingimporttime# 方式一直接传入函数defworker(name,seconds):time.sleep(seconds)print(f{name}完成)t1threading.Thread(targetworker,args(任务1,1))t1.start()t1.join()# 等待线程结束# 方式二继承 Thread 类classMyThread(threading.Thread):defrun(self):foriinrange(3):time.sleep(0.5)print(f{self.name}运行中{i})t2MyThread()t2.start()t2.join()2.2 多线程加速 I/O 任务importthreadingimporttimedefdownload(name,delay):time.sleep(delay)# 模拟网络请求print(f{name}下载完成耗时{delay}s)tasks[(文件A,2),(文件B,1),(文件C,3)]threads[]starttime.time()forname,delayintasks:tthreading.Thread(targetdownload,args(name,delay))t.start()threads.append(t)fortinthreads:t.join()print(f总耗时{time.time()-start:.1f}s)# 约 3s 而非 6s三、线程安全与锁多个线程同时修改共享数据可能出错需要加锁保护importthreading counter0lockthreading.Lock()defincrement(n):globalcounterfor_inrange(n):withlock:# 加锁保护临界区counter1threads[threading.Thread(targetincrement,args(100000,))for_inrange(10)]fortinthreads:t.start()fortinthreads:t.join()print(counter)# 正确结果 1000000四、线程池ThreadPoolExecutor手动管理线程较繁琐推荐使用线程池fromconcurrent.futuresimportThreadPoolExecutorimporttimedeftask(i):time.sleep(0.5)returni*iwithThreadPoolExecutor(max_workers4)aspool:# 提交单个任务futurepool.submit(task,5)print(future.result())# 25# 批量提交resultslist(pool.map(task,range(6)))print(results)# [0, 1, 4, 9, 16, 25]五、多进程multiprocessingPython 的 GIL全局解释器锁使多线程无法真正并行执行 CPU 密集型任务此时应使用多进程frommultiprocessingimportProcessimportosdefcompute(name):print(f进程{name}PID{os.getpid()})totalsum(range(10**7))print(f{name}计算结果{total})if__name____main__:processes[Process(targetcompute,args(fP{i},))foriinrange(4)]forpinprocesses:p.start()forpinprocesses:p.join()print(所有进程执行完毕)六、进程池ProcessPoolExecutorfromconcurrent.futuresimportProcessPoolExecutordefheavy_calc(x):returnsum(range(x))withProcessPoolExecutor(max_workers4)aspool:resultslist(pool.map(heavy_calc,[10**6]*4))print(results)七、如何选择线程还是进程场景推荐原因网络请求、文件读写等 I/O 密集多线程 / 异步GIL 影响小线程开销小CPU 计算密集如图像处理、算法多进程绕过 GIL利用多核 CPU任务数很多线程池 / 进程池复用资源避免频繁创建销毁八、实战并发下载器综合运用线程池写一个模拟并发下载器fromconcurrent.futuresimportThreadPoolExecutorimporttimeimportrandomdefdownload_file(url):模拟下载文件sizerandom.randint(1,10)time.sleep(size*0.1)returnf{url}下载完成{size}MBurls[fhttps://example.com/file{i}.zipforiinrange(10)]starttime.time()withThreadPoolExecutor(max_workers5)aspool:resultslist(pool.map(download_file,urls))forrinresults:print(r)print(f全部下载完成总耗时{time.time()-start:.1f}s)总结本篇介绍了多线程threading、线程池、多进程multiprocessing、进程池、锁机制以及线程/进程的选择策略并用并发下载器串联实战。下一篇将介绍数据库操作敬请期待

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/10/5 3:18:56
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/10/5 3:42:18
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/10/5 19:39:38
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/10/5 16:06:34
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/5 5:51:09
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/10/5 5:40:36

日新闻

周新闻

月新闻