• python3 进程池的同步调用


    # coding:utf-8
    import os
    import time
    from multiprocessing import Pool
    
    
    def func(n):
        print("%s:%s" % (os.getpid(), n))
        return n**2
    
    def func2(n):
        print("%s:%s" % (os.getpid(), n))
        time.sleep(1)
        return n**2
    
    
    if __name__ == '__main__':
        start_time = time.time()
        pool = Pool(5)  # 进程池中从无到有创建5个进程,以后一直是这5个进程在执行任务
        res_lst = []
        for i in range(10):
            res = pool.apply(func, args=(i,))  # 同步调用,直到本次任务执行完毕拿到res,等待任务func执行的过程中可能有阻塞也可能没有阻塞
                                        # 但不管该任务是否存在阻塞,同步调用都会在原地等着
            res_lst.append(res)
        print(res_lst)
        print("无阻塞进程池的执行时间:", time.time() - start_time)
    
        s_time = time.time()
        pool2 = Pool(5)  # 进程池中从无到有创建5个进程,以后一直是这5个进程在执行任务
        res_lst2 = []
        for i in range(10):
            res = pool2.apply(func2, args=(i,))  # 同步调用,直到本次任务执行完毕拿到res,等待任务func2执行的过程中可能有阻塞也可能没有阻塞
                                        # 但不管该任务是否存在阻塞,同步调用都会在原地等着
            res_lst2.append(res)
        print(res_lst2)
        print("有阻塞进程池的执行时间:", time.time() - s_time)
    
    # 9156:0
    # 9156:1
    # 9156:2
    # 9156:3
    # 9156:4
    # 9156:5
    # 9156:6
    # 9156:7
    # 9156:8
    # 9156:9
    # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    # 无阻塞进程池的执行时间: 0.515625
    # 5816:0
    # 3324:1
    # 3312:2
    # 8228:3
    # 9976:4
    # 5816:5
    # 3324:6
    # 3312:7
    # 8228:8
    # 9976:9
    # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    # 有阻塞进程池的执行时间: 10.421875
  • 相关阅读:
    非常实用的php各种文件操作函数
    两个自用的Dota2 自走棋辅助工具:阵容模拟器与UI Mod插件
    Scratch 数字游戏
    初识Scratch 3.0
    何时重头来
    cocos2d-x 3.0 Armature jsb 初体验
    cocosbuilder中的Callbacks和sound effects
    cocos2dx js文件加密为jsc文件
    cocos2dx jsb 在IOS与安卓下的一些不同之处
    安卓打包记录
  • 原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10986600.html
Copyright © 2020-2023  润新知