1. 程式人生 > 其它 >解決在window系統下建立多程序的出現RuntimeError的問題

解決在window系統下建立多程序的出現RuntimeError的問題

技術標籤:多工python多執行緒window

解決在window系統下建立多程序的出現RuntimeError的問題。

今天在做python建立程序池的時候出現了以下的錯誤,

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.

檢視程式碼:

# -*- coding:UTF-8 -*-
from multiprocessing import Pool
import os,time,random

def worker(msg):
    t_start = time.time()
    print('%s開始執行,程序號為%d' % (msg,os.getpid()))
    # random.random() 隨機生成0-1之間的浮點數
    time.sleep(random.random()*2)
    t_stop = time.time()
    print(msg,'執行完畢,耗時%0.2f' %
(t_stop-t_start)) po = Pool(2) #定義一個程序池,最大程序數為3 for i in range(0, 10): # Pool().apply_async(呼叫的目標,(傳遞給目標的引數元祖,)) # 每次迴圈將會用空閒的子程序去呼叫目標 po.apply_async(worker, (i,)) print('開始') po.close() #關閉程序池,關閉後po不在接收新的請求 po.join() #等待po中所有子程序執行完畢,必須放在close語句之後 print('結束')

原因是在window系統下,多執行緒需要在main函式下執行,解決辦法就是新增main函式。程式碼如下:

# -*- coding:UTF-8 -*-
from multiprocessing import Pool
import os,time,random

def worker(msg):
    t_start = time.time()
    print('%s開始執行,程序號為%d' % (msg,os.getpid()))
    # random.random() 隨機生成0-1之間的浮點數
    time.sleep(random.random()*2)
    t_stop = time.time()
    print(msg,'執行完畢,耗時%0.2f' % (t_stop-t_start))

if __name__ == '__main__':
    po = Pool(2) #定義一個程序池,最大程序數為3
    for i in range(0, 10):
        # Pool().apply_async(呼叫的目標,(傳遞給目標的引數元祖,))
        # 每次迴圈將會用空閒的子程序去呼叫目標
        po.apply_async(worker, (i,))
    print('開始')
    po.close() #關閉程序池,關閉後po不在接收新的請求
    po.join() #等待po中所有子程序執行完畢,必須放在close語句之後
    print('結束')

執行成功:
在這裡插入圖片描述