Python進程Multiprocessing模塊原理解析
先看看下面的幾個方法:
star() 方法啟動進程, join() 方法實現(xiàn)進程間的同步,等待所有進程退出。 close() 用來阻止多余的進程涌入進程池 Pool 造成進程阻塞。參數(shù):
target 是函數(shù)名字,需要調用的函數(shù)
args 函數(shù)需要的參數(shù),以 tuple 的形式傳入
用法:
multiprocessing.Process(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
寫一個的例子:
from multiprocessing import Poolimport os,timedef pr(str): print('The ' + str + ' is %s' %(os.getpid())) time.sleep(1) print('The ' + str + ' is close')if __name__ == '__main__': print(’-------------------------------’) print('the current pid: '+ str(os.getpid())) # 默認為自己電腦的核數(shù) p = Pool(2) for i in range(5): p.apply_async(pr,args=(’xdxd’,)) p.close() p.join() print('----------close-----------------')
通過結果可以看出,是2個進程同時啟動,同時啟動的進程數(shù)與pool中設置的數(shù)量和自己電腦的核數(shù)有關
結果:
-------------------------------the current pid: 9562The xdxd is 9563The xdxd is 9564The xdxd is closeThe xdxd is closeThe xdxd is 9563The xdxd is 9564The xdxd is closeThe xdxd is closeThe xdxd is 9563The xdxd is close----------close-----------------
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. Python2.6版本pip安裝步驟解析2. python公司內項目對接釘釘審批流程的實現(xiàn)3. python中Ansible模塊的Playbook的具體使用4. Python自動化之定位方法大殺器xpath5. Python本地及虛擬解釋器配置過程解析6. Python 利用flask搭建一個共享服務器的步驟7. 基于python實現(xiàn)matlab filter函數(shù)過程詳解8. Python中Anaconda3 安裝gdal庫的方法9. python自動化測試三部曲之request+django實現(xiàn)接口測試10. Python importlib模塊重載使用方法詳解
