1. 程式人生 > >多程序方法multiprocessing的Process使用錯誤

多程序方法multiprocessing的Process使用錯誤

想要按照書上測試多程序模組multiprocessing時,會發現使用錯誤
from multiprocessing import Process
import time

def test():
    while True:
        print("uuuuu")
        time.sleep(1)

p=Process(target=test)
p.start()#讓這個程序執行程式碼
while True:
    print("testtest")
    time.sleep(1)
結果會出現RuntimeError錯誤,An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.


        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:


            if __name__ == '__main__':
                freeze_support()
                ...


        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
程式無法正常執行,之後根據報錯資訊,修改部分程式碼,在多程序模組放在if __name__ == '__main__':內,即可正常執行,原理不明
from multiprocessing import Process
import time

def test():
    while True:
        print("uuuuu")
        time.sleep(1)
if __name__ == '__main__':
    p=Process(target=test)
    p.start()#讓這個程序執行程式碼
    while True:
        print("testtest")
        time.sleep(1)