python進程池 使用Queue實現計數功能

多進程中各個進程間相互隔離,進程間通訊須要使用到通道。python

多進程中使用Queue實現進程中通訊app

from multiprocessing import Process,Queue
import time ,random

def f(q, ):
    for i in range(10):
        n = q.get()
        n+=1
        q.put( n)
        print("計數",n)
        print('subpro',id(q))
        time.sleep(random.random())

if __name__=='__main__':
    q = Queue()
    q.put(0)
    print('mainpro',id(q))
    lst = []
    for i in range(3):
        p = Process(target=f, args=(q,))  # 必須把q傳進去,由於不一樣進程間內存是不共享的
        lst.append(p)
        p.start()
    for i in lst:
        i.join()
    print("總數",q.get())

使用進程池時,使用它Queue會出錯,須要使用Managerdom

from multiprocessing import Pool,Manager
import time ,random

def f(q, ):
    for i in range(10):
        n = q.get()
        n+=1
        q.put( n)
        print("計數",n)
        print('subpro',id(q))
        time.sleep(random.random())

if __name__=='__main__':
    q = Manager().Queue()
    q.put(0)
    print('mainpro',id(q))
    pool = Pool(8)
    for x in range(50):
        # 添加進程入進程池,注意加"_async",apply爲阻塞版本,參數分別爲target和args
        result = pool.apply_async(f, (q,))
    pool.close()
    pool.join()
    print("總數",q.get())
相關文章
相關標籤/搜索