run啟動多進程
import os from multiprocessing import Process import time def foo(): print("{}--->pid---->{}".format("foo", os.getpid())) print(123) time.sleep(4) print("end123") def bar(): print("{}--->pid---->{}".format("bar", os.getpid())) print(456) time.sleep(3) print("end456") if __name__ == '__main__': p1 = Process(target=foo) p2 = Process(target=bar) p1.run() p2.run() print("main-------")
運行結果如圖:
start啟動多進程
import os from multiprocessing import Process import time def foo(): print("{}--->pid---->{}".format("foo", os.getpid())) print(123) time.sleep(4) print("end123") def bar(): print("{}--->pid---->{}".format("bar", os.getpid())) print(456) time.sleep(3) print("end456") if __name__ == '__main__': p1 = Process(target=foo) p2 = Process(target=bar) p1.start() p2.start() print("main-------")
運行結果如下:
總結
在多進程下run方法啟動相當於直接調用函數,並沒有真正意義上使用多進程,這一點我們可以通過pid看的出來。而start啟動卻是真正意義上調用了多進程,同樣我們可以通過pid看的出來
注意
import os from multiprocessing import Process import time def foo(): print("{}--->pid---->{}".format("foo", os.getpid())) print(123) time.sleep(4) print("end123") def bar(): print("{}--->pid---->{}".format("bar", os.getpid())) print(456) time.sleep(3) print("end456") p1 = Process(target=foo) p2 = Process(target=bar) p1.start() p2.start() print("main-------")
上面的代碼運行就會出現異常,這里的原因是python多進程只能在main函數下面調用