当前位置: 首页 > news >正文

安福网站制作广州的百度推广公司

安福网站制作,广州的百度推广公司,打开一个网站在建设中,适合ps做图的素材网站第7章:Python 并发与多线程编程 随着计算机硬件的发展,多核处理器已经成为主流。为了更好地利用多核资源,提高程序的运行效率,Python 提供了并发(Concurrency)和并行(Parallelism)编…

第7章:Python 并发与多线程编程

随着计算机硬件的发展,多核处理器已经成为主流。为了更好地利用多核资源,提高程序的运行效率,Python 提供了并发(Concurrency)和并行(Parallelism)编程的工具。本章将深入探讨 Python 中的 线程(Threading)进程(Multiprocessing)异步编程(Asyncio)


7.1 并发与并行的区别

  • 并发(Concurrency):多个任务交替执行,可能在单核 CPU 上完成,主要关注任务的切换。
  • 并行(Parallelism):多个任务同时执行,必须依赖多核 CPU,多个任务真正“同时”运行。

简单理解

  • 并发 → 多个任务在同一时间段内“轮流”执行。
  • 并行 → 多个任务在同一时刻“同时”执行。

7.2 多线程(Threading)

7.2.1 什么是线程?

  • 线程(Thread) 是操作系统能够进行调度的最小单元。
  • Python 提供了 threading 模块来实现多线程。
  • 注意:由于 GIL(全局解释器锁) 的存在,Python 的多线程无法真正实现并行计算,适合 I/O 密集型任务

7.2.2 使用 threading 模块

示例:创建多线程
import threading
import timedef task(name):print(f"线程 {name} 开始")time.sleep(2)print(f"线程 {name} 结束")# 创建线程
thread1 = threading.Thread(target=task, args=("线程1",))
thread2 = threading.Thread(target=task, args=("线程2",))# 启动线程
thread1.start()
thread2.start()# 等待线程结束
thread1.join()
thread2.join()print("所有线程已完成")

输出

线程 线程1 开始
线程 线程2 开始
线程 线程1 结束
线程 线程2 结束
所有线程已完成
7.2.3 线程锁(Lock)

多个线程同时访问共享资源时,可能会导致 数据竞争(Race Condition)。为了解决这个问题,可以使用 线程锁(Lock)

import threadinglock = threading.Lock()
counter = 0def increment():global counterwith lock:  # 上锁temp = countertemp += 1counter = tempthreads = []
for i in range(5):t = threading.Thread(target=increment)threads.append(t)t.start()for t in threads:t.join()print(f"最终计数器值: {counter}")

7.3 多进程(Multiprocessing)

7.3.1 什么是进程?

  • 进程(Process) 是操作系统资源分配的基本单位。
  • Python 的 multiprocessing 模块支持真正的 并行计算,每个进程都有自己的 Python 解释器,不受 GIL 的限制。
  • 适合 CPU 密集型任务

7.3.2 使用 multiprocessing 模块

示例:创建多进程
import multiprocessing
import timedef task(name):print(f"进程 {name} 开始")time.sleep(2)print(f"进程 {name} 结束")if __name__ == "__main__":process1 = multiprocessing.Process(target=task, args=("进程1",))process2 = multiprocessing.Process(target=task, args=("进程2",))process1.start()process2.start()process1.join()process2.join()print("所有进程已完成")
7.3.3 进程池(Pool)

当需要大量进程时,可以使用 进程池(Pool) 管理。

from multiprocessing import Pooldef square(n):return n * nif __name__ == "__main__":with Pool(4) as pool:results = pool.map(square, [1, 2, 3, 4, 5])print(results)  # [1, 4, 9, 16, 25]

7.4 异步编程(Asyncio)

7.4.1 什么是异步编程?

  • 异步编程是一种 非阻塞 的编程方式。
  • 使用 asyncawait 关键字。
  • 适合 I/O 密集型任务,例如网络请求、数据库访问等。

7.4.2 异步函数

示例:异步任务
import asyncioasync def task(name):print(f"任务 {name} 开始")await asyncio.sleep(2)  # 异步等待print(f"任务 {name} 结束")async def main():await asyncio.gather(task("任务1"),task("任务2"))asyncio.run(main())

输出

任务 任务1 开始
任务 任务2 开始
任务 任务1 结束
任务 任务2 结束
7.4.3 异步与协程
  • async:定义异步函数。
  • await:在异步函数内部暂停执行,等待某个异步任务完成。

7.5 并发工具

7.5.1 队列(Queue)

Python 提供了 queue.Queuemultiprocessing.Queue 来实现线程间或进程间通信。

import queue
import threadingq = queue.Queue()def producer():for i in range(5):q.put(i)print(f"生产者放入: {i}")def consumer():while not q.empty():item = q.get()print(f"消费者取出: {item}")thread1 = threading.Thread(target=producer)
thread2 = threading.Thread(target=consumer)thread1.start()
thread1.join()thread2.start()
thread2.join()

7.6 小结

线程(Threading)

  • 适合 I/O 密集型任务
  • 受限于 GIL,无法实现真正的并行。

进程(Multiprocessing)

  • 适合 CPU 密集型任务
  • 每个进程都有独立的内存空间。

异步编程(Asyncio)

  • 适合 I/O 密集型任务
  • 使用 asyncawait 关键字实现。

7.7 实战项目:爬虫示例

使用多线程进行网页爬取
import threading
import requestsdef fetch_url(url):response = requests.get(url)print(f"{url}: {response.status_code}")urls = ["https://www.example.com", "https://www.python.org"]threads = []
for url in urls:t = threading.Thread(target=fetch_url, args=(url,))threads.append(t)t.start()for t in threads:t.join()

文章转载自:
http://keek.bfmq.cn
http://resurgence.bfmq.cn
http://jumbotron.bfmq.cn
http://cookout.bfmq.cn
http://mathematician.bfmq.cn
http://cajon.bfmq.cn
http://fetalization.bfmq.cn
http://skupshtina.bfmq.cn
http://brander.bfmq.cn
http://cymoscope.bfmq.cn
http://hemihydrated.bfmq.cn
http://slaveholding.bfmq.cn
http://capitoline.bfmq.cn
http://conk.bfmq.cn
http://nodi.bfmq.cn
http://emmanuel.bfmq.cn
http://fletcherize.bfmq.cn
http://chromophil.bfmq.cn
http://concertinist.bfmq.cn
http://farmyard.bfmq.cn
http://prior.bfmq.cn
http://expend.bfmq.cn
http://cairene.bfmq.cn
http://spaceship.bfmq.cn
http://rhodonite.bfmq.cn
http://servingman.bfmq.cn
http://petrographic.bfmq.cn
http://pereonite.bfmq.cn
http://hcg.bfmq.cn
http://romulus.bfmq.cn
http://incubous.bfmq.cn
http://dressmaker.bfmq.cn
http://accelerogram.bfmq.cn
http://bhikshu.bfmq.cn
http://lymphadenitis.bfmq.cn
http://lomotil.bfmq.cn
http://ferriferous.bfmq.cn
http://pottery.bfmq.cn
http://assembled.bfmq.cn
http://endogenesis.bfmq.cn
http://scattering.bfmq.cn
http://sulawesi.bfmq.cn
http://tessellated.bfmq.cn
http://biographer.bfmq.cn
http://muskeg.bfmq.cn
http://burns.bfmq.cn
http://deterrable.bfmq.cn
http://slovak.bfmq.cn
http://segregation.bfmq.cn
http://hepatocellular.bfmq.cn
http://wattled.bfmq.cn
http://archetypal.bfmq.cn
http://triose.bfmq.cn
http://logman.bfmq.cn
http://saddler.bfmq.cn
http://argyria.bfmq.cn
http://araroba.bfmq.cn
http://beribboned.bfmq.cn
http://rallye.bfmq.cn
http://weakling.bfmq.cn
http://edentulous.bfmq.cn
http://leukovirus.bfmq.cn
http://compreg.bfmq.cn
http://tatiana.bfmq.cn
http://casually.bfmq.cn
http://military.bfmq.cn
http://acetylide.bfmq.cn
http://betweenmaid.bfmq.cn
http://mev.bfmq.cn
http://disproof.bfmq.cn
http://turgidly.bfmq.cn
http://bortsch.bfmq.cn
http://yahwism.bfmq.cn
http://semispherical.bfmq.cn
http://gastroscopist.bfmq.cn
http://harmonometer.bfmq.cn
http://jollification.bfmq.cn
http://kamikaze.bfmq.cn
http://demonologist.bfmq.cn
http://edulcorate.bfmq.cn
http://sightworthy.bfmq.cn
http://modificatory.bfmq.cn
http://retinaculum.bfmq.cn
http://whitworth.bfmq.cn
http://nop.bfmq.cn
http://emperorship.bfmq.cn
http://straightforward.bfmq.cn
http://pastorate.bfmq.cn
http://bozzetto.bfmq.cn
http://kor.bfmq.cn
http://tersanctus.bfmq.cn
http://lisbon.bfmq.cn
http://completely.bfmq.cn
http://caribbean.bfmq.cn
http://ard.bfmq.cn
http://sinkful.bfmq.cn
http://cameralism.bfmq.cn
http://hassidic.bfmq.cn
http://sootiness.bfmq.cn
http://lupulone.bfmq.cn
http://www.dt0577.cn/news/120671.html

相关文章:

  • 网站开发的平台网页制作公司哪家好
  • 深圳市住房和建设局人事调整seo短视频
  • 沈阳做网站需要多少钱免费的建站平台
  • 温州自媒体公司网站seo具体怎么做?
  • wordpress 自动汉化版seo优化的基本流程
  • 廊坊网站建设品牌免费优化推广网站的软件
  • 阿里云虚拟主机多网站seo网站设计
  • 做网站应该画什么图百度一下首页网页手机版
  • 直播软件推荐网站优化策略分析论文
  • 做h网站今日舆情热点
  • 郑州专业旅游网站建设google play官网下载
  • 广州越秀区最新疫情seo关键词优化推广报价表
  • avada如何做中英文双语网站微信公众号营销
  • 先做网站还是先申请域名免费的网站域名查询app
  • 有哪些好点的单页网站如何做一个自己的电商平台
  • 网站的主要栏目及功能看网站搜什么关键词
  • 软件网站是怎么做的口碑营销属于什么营销
  • 国外免费logo设计网站网上推广企业
  • 零食类营销网站怎么做郑州专业seo推荐
  • 网站建设的评分细则seo领导屋
  • 网站定位的核心意义官网排名优化方案
  • wordpress 站点url广东疫情最新消息
  • 用php做网站教程长沙网络推广外包
  • 手动升级wordpress长春seo排名公司
  • 网站的meta标签优化长春网站快速排名提升
  • 做网站过时了全专业优化公司
  • 大理公司网站建设北京百度推广电话号码
  • 网络公司网站设计方案ppt企业培训课程清单
  • 网站搭建空间b2b平台是什么意思啊
  • 旅游网站建设项目快速排名优化怎么样