Python_報錯:line XXX, in join assert self._state in (CLOSE, TERMINATE) AssertionError


Python_報錯:

line XXX, in join
assert self._state in (CLOSE, TERMINATE)
AssertionError

源碼:

#encoding=utf-8
import time
from multiprocessing import Pool
def run(fn):
    #fn: 函數參數是數據列表的一個元素
    time.sleep(1)
    return fn * fn

if __name__ == "__main__":
    testFL = [1,2,3,4,5,6]
    print ('Single process execution sequence:') #順序執行(也就是串行執行,單進程)
    s = time.time()
    for fn in testFL:
        run(fn)
    e1 = time.time()
    print(u"順序執行時間:",int(e1-s))

    print('concurrent:') #創建多個進程,並行執行
    pool = Pool(5) #創建擁有5個進程數量的進程池
    #testFL:要處理的數據列表,run:處理testFL列表中數據的函數
    rl = pool.map(run,testFL)
    #pool.close()#關閉進程池,不再接受新的任務,join之前必須加上close(),否則會報錯
    pool.join()#主進程阻塞等待子進程的退出
    e2 = time.time()
    print(u"並行執行時間:",int(e2 - e1))
    print(rl)

原因:在進程池操作join()時。需在前面加上pool.close()即可

 

#encoding=utf-8
import time
from multiprocessing import Pool
def run(fn):
    #fn: 函數參數是數據列表的一個元素
    time.sleep(1)
    return fn * fn

if __name__ == "__main__":
    testFL = [1,2,3,4,5,6]
    print ('Single process execution sequence:') #順序執行(也就是串行執行,單進程)
    s = time.time()
    for fn in testFL:
        run(fn)
    e1 = time.time()
    print(u"順序執行時間:",int(e1-s))

    print('concurrent:') #創建多個進程,並行執行
    pool = Pool(5) #創建擁有5個進程數量的進程池
    #testFL:要處理的數據列表,run:處理testFL列表中數據的函數
    rl = pool.map(run,testFL)
    pool.close()#關閉進程池,不再接受新的任務,join之前必須加上close(),否則會報錯
    pool.join()#主進程阻塞等待子進程的退出
    e2 = time.time()
    print(u"並行執行時間:",int(e2 - e1))
    print(rl)

 

結果:

D:\Python36\python.exe D:/Python36/test_mysql/test_0810_01.py
Single process execution sequence:
順序執行時間: 6
concurrent:
並行執行時間: 2
[1, 4, 9, 16, 25, 36]

Process finished with exit code 0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM