您好,登錄后才能下訂單哦!
多進(jìn)程:主要運(yù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)程{}運(yù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()
線程池:主要運(yùn)用了未來模塊!下面例子,第一個(gè)是正常,第二第線程池,第三個(gè)用運(yùn)行了2個(gè)線程池,會(huì)排隊(duì)
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)程使用及線程池的使用方法代碼詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。