• Python_多进程_pool进程池


    多进程典型案例:

    1、将子进程的进程名作为列表中的元素,在父进程中遍历(异步)执行

    #coding: utf-8
    from multiprocessing import Pool
    import os, time, random
    #将函数打包成列表中的元素,再(异步)遍历执行
    
    def zhangsan():
        print ("
    Run task 张三-%s" %(os.getpid())) #os.getpid()获取当前的进程的ID
        start = time.time()
        time.sleep(random.random() * 10) #random.random()随机生成0-1之间的小数
        end = time.time()
        print ('Task 张三 runs %0.2f seconds.' %(end - start))
    
    def lisi():
        print ("
    Run task 李四-%s" %(os.getpid()))
        start = time.time()
        time.sleep(random.random() * 40)
        end=time.time()
        print ('Task 李四 runs %0.2f seconds.' %(end - start))
    
    def wangwu():
        print ("
    Run task 王五-%s" %(os.getpid()))
        start = time.time()
        time.sleep(random.random() * 30)
        end = time.time()
        print ('Task 王五 runs %0.2f seconds.' %(end - start))
    
    def zhaoliu():
        print ("
    Run task 赵六-%s" %(os.getpid()))
        start = time.time()
        time.sleep(random.random() * 20)
        end = time.time()
        print ('Task 赵六 runs %0.2f seconds.' %(end - start))
            
    if __name__=='__main__':
        function_list=  [zhangsan, lisi, wangwu, zhaoliu] 
        print ("parent process %s" %(os.getpid()))
    
        pool=Pool(4)
        for func in function_list:
            pool.apply_async(func)     #Pool执行函数,apply执行函数,当有一个进程执行完毕后,会添加一个新的进程到pool中
    
        print ('等待所有子进程执行……')
        pool.close()
        '''
        调用join之前,一定要先调用close() 函数,否则会出错,
        close()执行后不会有新的进程加入到pool,join函数等待素有子进程结束
        '''
        pool.join()    
        print ('子进程执行完毕')
  • 相关阅读:
    时间戳 时间 相互转换
    CS Academy Remove Update
    一周水题集锦 2017 9.4
    计蒜客 16877 卡牌游戏
    计蒜客 16876 韩梅梅的抽象画
    九度OJ 题目1534:数组中第K小的数字
    CS Academy Switch the Lights
    CF AIM Tech Round 4 C. Sorting by Subsequences
    CF Round 430 C. Ilya And The Tree
    CS Academy Round 44 Check DFS
  • 原文地址:https://www.cnblogs.com/hellangels333/p/8178568.html
Copyright © 2020-2023  润新知