python基础 -- Pool

2018-01-25  本文已影响0人  fada492daf5b

1. 作用

线程池,创建大量线程

2. 操作

# Pool
# 进程池
from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print('Run task {}({})...'.format(name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task {} runs {:0.2f} seconds.'.format(name, (end - start)))

if __name__ == '__main__':
    print('Parent process {}.'.format(os.getpid()))
    p = Pool(4)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,)) # 添加线程
    print('Waiting for all subprocesses done...')
    p.close() # 关闭线程池,不能在添加线程
    p.join() # 等待所有线程结束,必须先调用close
    print('All subprocesses done.')

上一篇下一篇

猜你喜欢

热点阅读