pythonにおけるmultiprocessingにおけるPoolの理解

1263 ワード

         ,           ,                 ,                   multiprocessing  Process        ,      ,     ,             
  ,      Pool       。
Pool                ,     Cpu   。         Pool  ,       ,    
               ;                   ,         ,         ,    
        。
#! usr/bin/python3.6
# -*- coding:utf-8 -*-
import time
import os
import random
from multiprocessing import Pool
def run_task(name):
    print("Task %s (pid=%s) is running..." %(name, os.getpid()))
    time.sleep(random.random()*3)
    print("Task %s end." %name)

if __name__ == '__main__':
    print("Current process %s" %os.getpid())
    p = Pool(processes= 3)
    for i in range(5):
        p.apply_async(run_task, args= (i,))
    print("Waiting for all subprocesses done...")
    p.close()
    p.join()
    print("All subprocess done.")

出力結果を下図に示します
Current process 8248
Waiting for all subprocesses done...
Task 0 (pid=1064) is running...
Task 1 (pid=19708) is running...
Task 2 (pid=19376) is running...
Task 0 end.
Task 3 (pid=1064) is running...
Task 3 end.
Task 4 (pid=1064) is running...
Task 4 end.
Task 1 end.
Task 2 end.
All subprocess done.