Python使用concurrent.futures模塊實現(xiàn)多進(jìn)程多線程編程
Python的concurrent.futures模塊可以很方便的實現(xiàn)多進(jìn)程、多線程運行,減少了多進(jìn)程帶來的的同步和共享數(shù)據(jù)問題。
Executor是一個抽象類,表示一個可執(zhí)行的上下文。Future則代表一個將要執(zhí)行的任務(wù),并提供了一些方法來獲取任務(wù)的狀態(tài)和結(jié)果。ThreadPoolExecutor是Executor的一個具體實現(xiàn)類,它使用線程池來執(zhí)行任務(wù)。
多線程
from concurrent.futures import ThreadPoolExecutor import time # 任務(wù)函數(shù) def task(name): print(f"任務(wù){(diào)name}開始執(zhí)行") time.sleep(2) print(f"任務(wù){(diào)name}執(zhí)行完畢") return True # 創(chuàng)建線程池 executor = ThreadPoolExecutor(max_workers=2) # 提交任務(wù) futures = [] for i in range(5): future = executor.submit(task, f"任務(wù){(diào)i + 1}") futures.append(future) # 等待所有任務(wù)完成 executor.shutdown() # 打印任務(wù)結(jié)果 for future in futures: print(future.result())
首先創(chuàng)建線程池:ThreadPoolExecutor對象executor,
然后提交任務(wù)列表:submit到線程池返回future,加入任務(wù)列表。
設(shè)置等待所有任務(wù)完成:executor.shutdown(),
最后查看執(zhí)行結(jié)果:future.result()。
多進(jìn)程
這里改用了ProcessPoolExecutor線程池。
import os import random import time from concurrent.futures import ProcessPoolExecutor def task(n): print('%s is runing' % os.getpid()) time.sleep(random.randint(1, 3)) return n ** 2 if __name__ == '__main__': executor = ProcessPoolExecutor(max_workers=3) futures = [] for i in range(11): future = executor.submit(task, i) futures.append(future) executor.shutdown(True) for future in futures: print(future.result())
add_done_callback設(shè)置回調(diào)函數(shù)
import os from concurrent.futures import ProcessPoolExecutor import requests def get_page(url): print('<進(jìn)程%s> get %s' % (os.getpid(), url)) respone = requests.get(url) if respone.status_code == 200: return {'url': url, 'text': respone.text} def parse_page(res): res = res.result() print('<進(jìn)程%s> parse %s' % (os.getpid(), res['url'])) parse_res = 'url:<%s> size:[%s]\n' % (res['url'], len(res['text'])) with open('db.txt', 'a') as f: f.write(parse_res) if __name__ == '__main__': urls = [ 'https://www.baidu.com', 'https://www.python.org', 'https://www.openstack.org', 'https://help.github.com/', 'http://www.sina.com.cn/' ] p = ProcessPoolExecutor(3) for url in urls: p.submit(get_page, url).add_done_callback(parse_page) # parse_page拿到的是一個future對象obj,需要用obj.result()拿到結(jié)果
相關(guān)鏈接
到此這篇關(guān)于Python使用concurrent.futures模塊實現(xiàn)多進(jìn)程多線程編程的文章就介紹到這了,更多相關(guān)Python concurrent.futures內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?shapefile轉(zhuǎn)GeoJson的2種方式實例
geojson是地圖可視化系統(tǒng)中最常用的地理數(shù)據(jù)格式,幾乎所有主流地圖可視化庫或框架都支持geojson數(shù)據(jù)的加載,下面這篇文章主要給大家介紹了關(guān)于Python?shapefile轉(zhuǎn)GeoJson的2種方式的相關(guān)資料,需要的朋友可以參考下2023-03-03高質(zhì)量Python代碼編寫的5個優(yōu)化技巧
這篇文章主要為大家詳細(xì)介紹了編寫高質(zhì)量Python代碼的5個優(yōu)化技巧,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11python內(nèi)置函數(shù)compile(),complex()的使用
這篇文章主要為大家詳細(xì)介紹了python內(nèi)置函數(shù)compile(),complex()的使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06Pytorch中的 torch.distributions庫詳解
這篇文章主要介紹了Pytorch中的 torch.distributions庫,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02