随笔 - 31  文章 - 0  评论 - 0  阅读 - 2444

<2> 线程池---ThreadPoolExecutor

复制代码
 1 import time
 2 from concurrent.futures import ThreadPoolExecutor, as_completed, ProcessPoolExecutor
 3 
 4 
 5 class Spider:
 6     
 7     executor = ThreadPoolExecutor(max_workers=10)
 8     # executor = ProcessPoolExecutor(max_workers=10)
 9     
10     def __init__(self):
11         pass
12 
13     def request(self, url, second): # 模拟耗时任务
14         time.sleep(second)
15         return url, second
16 
17     def run(self):
18         all_tasks = []
19         for index in range(100):  # index ----------> 模拟url
20             task = self.executor.submit(self.http_request, index, 2)
21             all_tasks.append(task)
22 
23         for result in as_completed(all_tasks):
24             exception = result.exception()
25             if exception:
26                 pass
27             data = result.result()
28             print(data)
29 
30 
31 if __name__ == '__main__':
32     s = Spider()
33     s.run()
复制代码

 

posted on   不是霉蛋  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示