07进程池线程池
提交任务的方式:
同步调用:提交任务后,就在原地等待,等待任务执行完毕,拿到任务的返回值,才能继续执行下一行代码,导致程序串行
异步调用+回调机制:提交任务后,不在原地等待,任务一旦执行完毕就会触发回调函数的执行,程序是并发执行
进程的执行调用:
阻塞:
非阻塞:
进程池:
同步调用实例:result()取得结果,导致同步调用
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import os, time, random def task(n): print('{} is running'.format(os.getpid())) time.sleep(random.randint(1,3)) return n**2 def handle(res): print('handle res', res) if __name__ == '__main__': pool = ProcessPoolExecutor(4) for i in range(5): #result(),取得结果,所以此时是同步调用,要等待res的结果 res = pool.submit(task,i).result() # print(res) handle(res) pool.shutdown(wait=True)#wait=True,等待池内所有任务执行完毕回收完资源后才继续 print('主')
异步调用实例,不用result取得结果,回调机制处理结果
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import os, time, random def task(n): print('{} is running'.format(os.getpid())) time.sleep(random.randint(1,3)) # res = n**2 # handle(res) return n**2 def handle(res): res = res.result() print('handle res', res) if __name__ == '__main__': pool = ProcessPoolExecutor(2) for i in range(5): # pool.submit(task,i).add_done_callback(handle)#添加回调函数,等于下面两句 obj = pool.submit(task,i) obj.add_done_callback(handle)#handle(obj) pool.shutdown(wait=True)#wait=True,等待池内所有任务执行完毕回收完资源后才继续 print('主')
线程池
from concurrent.futures import ThreadPoolExecutor from threading import current_thread import requests import time def get_page(url): print('{} get {}'.format(current_thread().getName(), url)) time.sleep(2) response = requests.get(url) if response.status_code == 200: return {'url':url, 'text':response.text} def parse_page(res): res = res.result() print('parse:{},text:{}'.format(res['url'],len(res['text']))) if __name__ == '__main__': urls = [ 'https://www.baidu.com', 'https://www.python.org', 'https://i-beta.cnblogs.com/', 'https://www.cnblogs.com/xiaoyuanqujing/p/11636160.html', 'https://www.cnblogs.com/linhaifeng/p/7278389.html' ] pools = ThreadPoolExecutor(2) for url in urls: pools.submit(get_page, url).add_done_callback(parse_page)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】