本文的文字及圖片來源於網絡,僅供學習、交流使用,不具備任何商業用途,版權歸原做者全部,若有問題請及時聯繫咱們以做處理網絡
multiprocessing模塊就是跨平臺版本的多進程模塊,提供了一個Process類來表明一個進程對象,這個對象能夠理解爲是一個獨立的進程,能夠執行另外的事情app
# -*- coding:utf-8 -*-from multiprocessing import Processimport timedef run_proc(): """子進程要執行的代碼""" while True: print("----2----") time.sleep(1)if __name__=='__main__': p = Process(target=run_proc) p.start() while True: print("----1----") time.sleep(1)
建立子進程時,只須要傳入一個執行函數和函數的參數,建立一個Process實例,用start()方法啓動dom
# -*- coding:utf-8 -*-from multiprocessing import Processimport osimport timedef run_proc():"""子進程要執行的代碼"""print('子進程運行中,pid=%d...' % os.getpid()) # os.getpid獲取當前進程的進程號print('子進程將要結束...')if __name__ == '__main__':print('父進程pid: %d' % os.getpid()) # os.getpid獲取當前進程的進程號p = Process(target=run_proc) p.start()
# -*- coding:utf-8 -*-from multiprocessing import Processimport osfrom time import sleepdef run_proc(name, age, **kwargs):for i in range(10):print('子進程運行中,name= %s,age=%d ,pid=%d...' % (name, age, os.getpid()))print(kwargs) sleep(0.2)if __name__=='__main__': p = Process(target=run_proc, args=('test',18), kwargs={"m":20}) p.start() sleep(1) # 1秒中以後,當即結束子進程 p.terminate() p.join() 運行結果: 子進程運行中,name= test,age=18 ,pid=45097... {'m': 20} 子進程運行中,name= test,age=18 ,pid=45097... {'m': 20} 子進程運行中,name= test,age=18 ,pid=45097... {'m': 20} 子進程運行中,name= test,age=18 ,pid=45097... {'m': 20} 子進程運行中,name= test,age=18 ,pid=45097... {'m': 20}
# -*- coding:utf-8 -*-from multiprocessing import Processimport osimport time nums = [11, 22]def work1():"""子進程要執行的代碼"""print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))for i in range(3): nums.append(i) time.sleep(1)print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))def work2():"""子進程要執行的代碼"""print("in process2 pid=%d ,nums=%s" % (os.getpid(), nums))if __name__ == '__main__': p1 = Process(target=work1) p1.start() p1.join() p2 = Process(target=work2) p2.start() 運行結果:in process1 pid=11349 ,nums=[11, 22]in process1 pid=11349 ,nums=[11, 22, 0]in process1 pid=11349 ,nums=[11, 22, 0, 1]in process1 pid=11349 ,nums=[11, 22, 0, 1, 2]in process2 pid=11350 ,nums=[11, 22]
可使用multiprocessing模塊的Queue實現多進程之間的數據傳遞,Queue自己是一個消息列隊程序。ide
咱們以Queue爲例,在父進程中建立兩個子進程,一個往Queue裏寫數據,一個從Queue裏讀數據:函數
from multiprocessing import Process, Queueimport os, time, random# 寫數據進程執行的代碼:def write(q):for value in ['A', 'B', 'C']:print('Put %s to queue...' % value) q.put(value) time.sleep(random.random())# 讀數據進程執行的代碼:def read(q):while True:if not q.empty(): value = q.get(True)print('Get %s from queue.' % value) time.sleep(random.random())else:breakif __name__=='__main__':# 父進程建立Queue,並傳給各個子進程:q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,))# 啓動子進程pw,寫入: pw.start() # 等待pw結束: pw.join()# 啓動子進程pr,讀取: pr.start() pr.join()# pr進程裏是死循環,沒法等待其結束,只能強行終止:print('')print('全部數據都寫入而且讀完')"""輸入以下: Put A to queue... Put B to queue... Put C to queue... Get A from queue. Get B from queue. Get C from queue. 全部數據都寫入而且讀完"""