python_多進程_Pool


Skip to end of metadata

1.apply/apply_async方法,每次只能向進程池分配一個任務,那如果想一次分配多個任務到進程池中,可以使用map/map_async方法。首先來看下map_async方法是如何定義的:

apply/apply_async使用循環創建,

map/map_async太複雜,不建議使用,需要計算參數列表的個數https://www.cnblogs.com/Tour/p/4564710.html


2.當直接通過pool+queue進行多進程操作,程序不會響應,隊列對象不能在父進程與子進程間通信,如果想要使用進程池中使用隊列則要使用multiprocess的Manager類

 

備註:網上有人這樣操作會有報錯提示:RuntimeError: Queue objects should only be shared between processes through inheritance

 

#本來我想要的是將會得到一個隊列,將其作爲參數傳入進程池子裏的每個子進程
#直接pool+queue,程序無響應,pw,pr直接沒有響應
#網上有人這樣操作會有報錯提示:RuntimeError: Queue objects should only be shared between processes through inheritance

 

from multiprocessing import Process, Queue,Pool,Manager
import os, time, random
 
# 寫數據進程執行的代碼:
def write(q):
    for value in ['A''B''C']:
        print(  'Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())
 
 
# 讀數據進程執行的代碼:
def read(q):
    while True:
        if not q.empty():
            value = q.get(True)
            print('Get %s from queue.' % value)
 
            time.sleep(random.random())
        else:
            break
 
 
if __name__ == '__main__':
    # 父進程創建Queue,並傳給各個子進程:
    # 父進程創建Queue,並傳給各個子進程:
    = Queue()
    = Pool()
    pw = p.apply_async(write, args=(q,))
    pr = p.apply_async(read, args=(q,))
    p.close()
    p.join()
    print('====================================')
    print('所有數據都寫入並且讀完')

 

#進程池中使用隊列則要使用multiprocess的Manager類,用Manage的實例去定義queue,程序運行結果與預期一致

 

if __name__ == '__main__':
    # 父進程創建Queue,並傳給各個子進程:
    # 父進程創建Queue,並傳給各個子進程:
    manager = Manager()
    = manager.Queue()
    = Pool()
    pw = p.apply_async(write, args=(q,))
    pr = p.apply_async(read, args=(q,))
    p.close()
    p.join()
    print('====================================')
    print('所有數據都寫入並且讀完')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章