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()  使得程序阻塞。

  • 相关阅读:
    python_6
    python_day4
    python_day3
    python_day2
    python
    python入门
    jQuery之前端国际化jQuery.i18n.properties
    转载!网页中插入百度地图
    jQuery.validate 中文API
    Web移动端Fixed布局的解决方案
  • 原文地址:https://www.cnblogs.com/Zhao159461/p/10752750.html
Copyright © 2011-2022 走看看