美文网首页
python基础 -- Pool

python基础 -- Pool

作者: fada492daf5b | 来源:发表于2018-01-25 12:23 被阅读0次

    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.')
    
    

    相关文章

      网友评论

          本文标题:python基础 -- Pool

          本文链接:https://www.haomeiwen.com/subject/waqvaxtx.html