在新創建的子行程中,會把父行程的所有資訊復制一份,它們之間的資料互不影響,
1.使用os.fork()創建
該方式只能用于Unix/Linux作業系統中,在windows不能用,
import os
# 注意,fork函式,只在Unix/Linux/Mac上運行,windows不可以
pid = os.fork()
# 子行程永遠回傳0,而父行程回傳子行程的ID,
if pid == 0:
print('子行程')
else:
print('父行程')
2.使用Process類類創建
multiprocessing模塊提供了一個Process類來代表一個行程物件,下面的例子演示了啟動一個子行程并等待其結束:
from multiprocessing import Process
import time
def test(name, age):
for i in range(5):
print("--test--%s\t%d" % (name, age))
time.sleep(1)
print("子行程結束")
if __name__ == '__main__':
p = Process(target=test, args=("aaa", 18))
p.start()
# 等待行程實體執?結束,或等待多少秒;
p.join() # 等待的最長時間
print("主行程結束")
"""
輸出結果:
--test--aaa 18
--test--aaa 18
--test--aaa 18
--test--aaa 18
--test--aaa 18
子行程結束
主行程結束
"""
join()方法表示主行程等待子行程執行完成后繼續往下執行,如果把join()注釋掉,則主行程開啟子行程后不停頓繼續往下執行,然后等待子行程完成程式結束,
把join()方法注釋掉的結果:
"""
輸出結果:
主行程結束
--test--aaa 18
--test--aaa 18
--test--aaa 18
--test--aaa 18
--test--aaa 18
子行程結束
"""
3.使用Process子類創建
創建新的行程還能夠使用類的方式,可以自定義一個類,繼承Process類,每次實體化這個類的時候,就等同于實體化一個行程物件,請看下面的實體:
from multiprocessing import Process
import time
import os
class MyProcess(Process):
def __init__(self):
# 如果子類要重寫__init__是必須要先呼叫父類的__init__否則會報錯
# Process.__init__(self)
super(MyProcess,self).__init__()
# 學習中遇到問題沒人解答?小編創建了一個Python學習交流群:711312441
# 重寫Porcess的run()方法
def run(self):
print("子行程(%s)開始執行,父行程(%s)" % (os.getpid(), os.getppid()))
for i in range(5):
print("--1--")
time.sleep(1)
if __name__ == '__main__':
t_start = time.time()
p = MyProcess()
p.start()
# p.join()
print("main")
for i in range(5):
print("--main--")
time.sleep(1)
4.使用行程池Pool創建
當需要創建的子行程數量不多時,可以直接利用multiprocessing中的Process動態成生多個行程,但如果是上百甚至上千個目標,手動的去創建行程的作業量巨大,此時就可以用到multiprocessing模塊提供的Pool方法,
初始化Pool時,可以指定一個最大行程數,當有新的請求提交到Pool中時,如果池還沒有滿,那么就會創建一個新的行程用來執行該請求;但如果池中的行程數已經達到指定的最大值,那么該請求就會等待,直到池中有行程結束,才會創建新的行程來執行,請看下面的實體:
from multiprocessing import Pool
import os
import time
def worker(num):
# for i in range(3):
print("----pid=%d num=%d---" % (os.getpid(), num))
time.sleep(1)
if __name__ == '__main__':
# 定義一個行程池,最大行程數3
pool = Pool(3)
for i in range(10):
print("---%d--" % i)
# 使用非阻塞方式呼叫func(并行執行),一般用這個,
# apply堵塞方式必須等待上一個行程退出才能執行下一個行程,用的不多,
pool.apply_async(worker, (i,))
# 關閉行程池
pool.close()
# 等待所有子行程結束,主行程一般用來等待
pool.join() # 行程池后面無操作時必須有這句
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556207.html
標籤:Python
上一篇:Conda 命令深入指南
下一篇:返回列表