1. 程式人生 > >if __name__ == '__main__':在一個多程序python程式中的必要性

if __name__ == '__main__':在一個多程序python程式中的必要性

import multiprocessing, time

def test(i):
    while 1:
        print(i)
        time.sleep(.2)

# if __name__ == '__main__': --- 去掉則會報錯
multiprocessing.Process(target=test, args=(1,)).start()
multiprocessing.Process(target=test, args=(2,)).start()

#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‘: 則會報錯。

子程序會在執行時拷貝當前主程序中的所有內容,這也就意味著當一個新的子程序被建立的時候,該子程序就會複製當前模組,當然也包括了以下兩行:

multiprocessing.Process(target=test, args=(1
,)).start() multiprocessing.Process(target=test, args=(2,)).start()

很顯然,這樣的寫法可能形成無限遞迴式地建立新的子程序。所以為了避免以上情況發生,我們在此引入了 if name == ‘main‘: 。

以上內容參考:
https://stackoverflow.com/questions/34223502/why-does-this-multiprocessing-code-fail