[英]I can't start two functions at the same time, with multiprocessing Python. Why?
我只想同時啟動 2 個功能,但它不起作用,這是我的代碼:
from multiprocessing import Process
import time as t
def print1():
print(1)
t.sleep(10)
def print2():
print(1)
t.sleep(10)
if __name__ == '__main__':
p1 = Process(target = print1)
p1.start()
p1.join()
p2 = Process(target = print2)
p2.start()
p2.join()
我在控制台上沒有任何問題,但 function 沒有同時啟動。 怎么了?
從這篇關於如何在 Python 中同時啟動所有進程而不是
p1 = Process(target = print1)
p1.start()
p1.join()
p2 = Process(target = print2)
p2.start()
p2.join()
做
p1 = Process(target = print1)
p2 = Process(target = print2)
p1.start()
p2.start()
p1.join()
p2.join()
然后在它之后運行另一個 function,你可以這樣做
p1 = Process(target = print1)
p2 = Process(target = print2)
p3 = Process(target = print3)
p1.start()
p2.start()
p1.join()
p2.join()
p3.start()
p3.join()
因為您正在使用.join()
。 根據文檔:
如果可選參數 timeout 為 None(默認值),則該方法會阻塞,直到調用其 join() 方法的進程終止。 如果超時為正數,則最多阻塞超時秒數。 請注意,如果其進程終止或方法超時,該方法將返回 None。 檢查進程的退出代碼以確定它是否終止。
因此,通過調用.join()
,您正在使進程阻塞直到它終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.