zoukankan      html  css  js  c++  java
  • 如何在进程池中实现并发,并且返回值是按照顺序返回?

    1.回调函数 add_done_callback()

    但是返回结果是无序的。

     1 import time
     2 import random
     3 from concurrent.futures import ProcessPoolExecutor
     4 def func1(n):
     5     time.sleep(random.random())
     6     print('in func1 %s'%n)
     7     return n*2
     8 
     9 def call_back(arg):
    10     print(arg.result())
    11 
    12 if __name__ == '__main__':
    13     p = ProcessPoolExecutor(4)
    14     for i in range(10):
    15         ret = p.submit(func1,i)
    16         ret.add_done_callback(call_back)#是乱序的
    View Code

    运行结果:

    2. 运用列表:

     1 import time
     2 import random
     3 from concurrent.futures import ProcessPoolExecutor
     4 def func1(n):
     5     time.sleep(random.random())
     6     print('in func1 %s'%n)
     7     return n*2
     8 
     9 def call_back(arg):
    10     print(arg.result())
    11 
    12 if __name__ == '__main__':
    13     p = ProcessPoolExecutor(4)
    14     # for i in range(10):
    15     #     ret = p.submit(func1,i)
    16     #     ret.add_done_callback(call_back)#是乱序的
    17     ret_l = []
    18     for i in range(10):
    19         ret = p.submit(func1, i)
    20         ret_l.append(ret)#实现了该列表的顺序不是乱序的,在for循环列表中直接放对象
    21         # print(ret)
    22     for r in ret_l:
    23         call_back(r)
    View Code

    运行结果:

     3.

     1 import time
     2 import random
     3 from concurrent.futures import ProcessPoolExecutor
     4 def func1(n):
     5     time.sleep(random.random())
     6     print('in func1 %s'%n)
     7     return n*2
     8 
     9 def call_back(arg):
    10     print(arg.result())
    11 
    12 if __name__ == '__main__':
    13     p = ProcessPoolExecutor(4)
    14     # for i in range(10):
    15     #     ret = p.submit(func1,i)
    16     #     ret.add_done_callback(call_back)#是乱序的
    17     ret_l = []
    18     for i in range(10):
    19         ret = p.submit(func1, i)
    20         call_back(ret)
    21         # ret_l.append(ret)#实现了该列表的顺序不是乱序的,在for循环列表中直接放对象
    22         # print(ret)
    23     # for r in ret_l:
    24     #     call_back(r)
    View Code

    运行结果:

    猜想的 不一定对,call_back(ret)接受的是对象  但是call_back函数需要打印ret.result()  使得程序阻塞。

  • 相关阅读:
    event的属性
    dom三个事件
    setInterval和setTimeout定时器
    eclipse编码格式设置
    eclipse Subversion Native Library Not Available
    NET Framework V4.0.30319
    eclipse配置tomcat
    eclipse Multiple annotations found at this line
    eclipse安装svn插件
    eclipse安装maven
  • 原文地址:https://www.cnblogs.com/Zhao159461/p/10752750.html
Copyright © 2011-2022 走看看