python多進(jìn)程使用及線程池的使用方法代碼詳解
多進(jìn)程:主要運行multiprocessing模塊
import os,time import sys from multiprocessing import Process class MyProcess(Process): """docstring for MyProcess""" def __init__(self, arg, callback): super(MyProcess, self).__init__() self.arg = arg self.callback = callback def run(self): self.callback(self.arg) def test(arg): print("子進(jìn)程{}開始>>> pid={}".format(arg,os.getpid())) for i in range(1,5): sys.stdout.write("子進(jìn)程{}運行中{}\r".format(arg,i)) sys.stdout.flush() time.sleep(1) def main(): print("主進(jìn)程開始>>> pid={}".format(os.getpid())) myp=MyProcess(1,test) myp.start() myp2=MyProcess(2,test) myp2.start() myp.join() myp2.join() print("主進(jìn)程終止") if __name__ == '__main__': main()
線程池:主要運用了未來模塊!下面例子,第一個是正常,第二第線程池,第三個用運行了2個線程池,會排隊
from concurrent.futures import ThreadPoolExecutor import time def sayhello(a): print("hello: "+a) time.sleep(2) def main(): seed=["a","b","c"] start1=time.time() for each in seed: sayhello(each) end1=time.time() print("time1: "+str(end1-start1)) start2=time.time() with ThreadPoolExecutor(3) as executor: for each in seed: executor.submit(sayhello,each) end2=time.time() print("time2: "+str(end2-start2)) start3=time.time() with ThreadPoolExecutor(2) as executor1: executor1.map(sayhello,seed) end3=time.time() print("time3: "+str(end3-start3)) if __name__ == '__main__': main()
總結(jié)
以上所述是小編給大家介紹的python多進(jìn)程使用及線程池的使用方法代碼詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
使用python搭建代理IP池實現(xiàn)接口設(shè)置與整體調(diào)度
在網(wǎng)絡(luò)爬蟲中,代理IP池是一個非常重要的組件,由于許多網(wǎng)站對單個IP的請求有限制,因此,我們需要一個代理IP池,在本文中,我們將使用Python來構(gòu)建一個代理IP池,然后,我們將使用這個代理IP池來訪問我們需要的數(shù)據(jù),文中有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下2023-12-12Python機(jī)器學(xué)習(xí)iris數(shù)據(jù)集預(yù)處理和模型訓(xùn)練方式
iris數(shù)據(jù)集包含150個樣本,每個樣本有4個特征及其類別信息,本文介紹了iris數(shù)據(jù)集的基本操作和如何使用knn模型進(jìn)行花卉種類預(yù)測,是機(jī)器學(xué)習(xí)中的經(jīng)典案例,適用于監(jiān)督式學(xué)習(xí)2024-10-10python程序中調(diào)用其他程序的實現(xiàn)
本文主要介紹了python程序中調(diào)用其他程序的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02django實現(xiàn)登錄時候輸入密碼錯誤5次鎖定用戶十分鐘
這篇文章主要介紹了django實現(xiàn)登錄時候輸入密碼錯誤5次鎖定用戶十分鐘,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11?cmd輸入python打開微軟應(yīng)用商店的解決方法
在命令控制行中輸入python想使用Python環(huán)境,卻意外打開了微軟自帶的應(yīng)用商店,十分苦惱,下面這篇文章主要給大家介紹了關(guān)于?cmd輸入python打開微軟應(yīng)用商店的解決方法,需要的朋友可以參考下2024-03-03