1. 程式人生 > >python使用多進程

python使用多進程

__main__ 不能 代碼 all %s get python 計算 lee

python多線程適合IO密集型場景,而在CPU密集型場景,並不能充分利用多核CPU,而協程本質基於線程,同樣不能充分發揮多核的優勢。

針對計算密集型場景需要使用多進程,python的multiprocessing與threading模塊非常相似,支持用進程池的方式批量創建子進程。

示例代碼:

import os
import random
import time
from multiprocessing import Pool
from time import ctime


def task(name):
    print(‘start task %s (%s)...‘ % (name, os.getpid()))

    start = time.time()
    time.sleep(random.random() * 3)

    print(‘end task %s runs %0.2f seconds.‘ % (name, (time.time() - start)))


if __name__ == ‘__main__‘:
    print(‘parent process %s.‘ % os.getpid())

    p = Pool()  # 初始化進程池
    for i in range(5):
        p.apply_async(task, args=(i,))  # 追加任務

    p.close()

    p.join()  # 等待所有結果執行完畢
    print(f‘all done at: {ctime()}‘)

註意:join()方法會等待所有子進程執行完畢,調用join()之前必須先調用close()

python使用多進程