Python multiprocessing (多進程)使用

官方文檔 https://docs.python.org/3.6/library/multiprocessing.html

from multiprocessing import Pool, Manager
import time, random, os

# 需要執行的函數
def f(x):
    time.sleep(random.randint(1, 3))
    return x, os.getpid()


# 回調函數
def p_callback(res):
    x, pid = res
    print("回調進程ID號:%s, 結果:%s" % (pid, x))


def m_callback(res):
    d, pid = res
    d.value += 1
    print("回調進程ID號:%s, 結果:%s" % (pid, d))


if __name__ == '__main__':
    with Pool(4) as p:
        print("----------map----------")
        # 會阻塞,直到所有的進程都執行完畢
        print(p.map(f, [1, 2, 3]))

        print("----------imap----------")
        # 阻塞懶惰map,需要調用結果next 驅動任務繼續執行
        it = p.imap(f, range(10))
        for x in it:# 這裏相當於主動調用了 next
            print("\t", x)

        print("----------imap_unordered----------")
        # 與map一樣都是阻塞懶惰模式,但是imap_unordered不保證結果順序
        it = p.imap_unordered(f, range(10))
        for x in it:
            print("\t", x)

    with Pool(4) as p:
        for i in range(10):
            # 異步,非阻塞方式執行,主進程需要等待子進程完成
            p.apply_async(f, (i,), callback=p_callback)

        print("-------- apply_async --------")
        p.close()
        p.join() # 主進程等待子進程結束

    # 進程共享對象
    with Manager() as m:
        v = m.Value('i', 0)  # i ctype int 類型
        # 支持類型:list,dict,Namespace,Lock, RLock,Semaphore,BoundedSemaphore,
        # Condition,Event,Barrier, Queue,Value和Array。例如,
        with Pool(4) as p:
            for i in range(10):
                p.apply_async(f, args=(v,), callback=m_callback)
            p.close()
            p.join()

結果如下:

D:\software\Anaconda3\pythonw.exe D:/workspace/PycharmProjects/DeltaGrad/trunk/strategy/load/thread_test.py
----------map----------
[(1, 12344), (2, 22720), (3, 21940)]
----------imap----------
     (0, 20732)
     (1, 12344)
     (2, 22720)
     (3, 21940)
     (4, 22720)
     (5, 21940)
     (6, 12344)
     (7, 22720)
     (8, 20732)
     (9, 12344)
----------imap_unordered----------
     (1, 21940)
     (2, 20732)
     (4, 21940)
     (0, 22720)
     (3, 12344)
     (8, 21940)
     (5, 20732)
     (7, 12344)
     (6, 22720)
     (9, 21940)
-------- apply_async --------
回調進程ID號:17424, 結果:1
回調進程ID號:21744, 結果:2
回調進程ID號:23220, 結果:0
回調進程ID號:17424, 結果:4
回調進程ID號:21744, 結果:5
回調進程ID號:1360, 結果:3
回調進程ID號:21744, 結果:8
回調進程ID號:23220, 結果:6
回調進程ID號:17424, 結果:7
回調進程ID號:1360, 結果:9
回調進程ID號:3164, 結果:Value('i', 1)
回調進程ID號:18120, 結果:Value('i', 2)
回調進程ID號:18116, 結果:Value('i', 3)
回調進程ID號:22108, 結果:Value('i', 4)
回調進程ID號:18120, 結果:Value('i', 5)
回調進程ID號:3164, 結果:Value('i', 6)
回調進程ID號:3164, 結果:Value('i', 7)
回調進程ID號:18116, 結果:Value('i', 8)
回調進程ID號:22108, 結果:Value('i', 9)
回調進程ID號:18120, 結果:Value('i', 10)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章