multiprocessing多執行緒未執行

UncoDong發表於2020-09-27

以下程式碼在Jupyter沒有任何輸出

# 1 匯入
import multiprocessing


import time
#唱歌
def sing( ):
    for i in range(3):
        print("唱歌...")
        time.sleep(0.5)
#跳舞
def dance( ):
    for i in range(3):
        print("跳舞...")
        time.sleep(0.5)

# 2. 使用程式類
sing_process = multiprocessing.Process (target=sing)
dance_process = multiprocessing.Process (target=dance)

# 3. 啟動程式
sing_process.start()
dance_process.start()

在這裡插入圖片描述

在這裡得到了答案https://zhidao.baidu.com/question/621802532293803652.html

這是因為multiprocessing模組在互動模式是不支援的,在 cmd 裡頭輸入 python xxx.py 來執行起來,你就可以看到子程式的執行了。

注意!如果多程式沒有放在主函式執行,會報以下錯誤

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.

start方法放在main中即可
在這裡插入圖片描述

在這裡插入圖片描述

相關文章