zoukankan      html  css  js  c++  java
  • concurrent.future

    concurrent.future module provides a high-level interface for asynchronously executing callables.

    Basic Format:

    from concurrent.future import ThreadPoolExecuor,ProcessPoolExecutor
    
    executor = ThreadPoolExecutor(max_workers=2)  #max_workers 为池中允许的线程数
    
    executor = ProcessPoolExecutor(max_workers=2)
    
    obj1 = executor.submit(function, arg1, arg2)  #提交子线程
    obj2 = executor.map(func,iterator)    #异步运行的map
    
    executor.shutdown(wait=True)   # 类似于pool.close()  pool.join()  等待所有子进程/线程运行完结果  当wait = False的时候结果会立刻返回,但pool依然会等到所有结果都得到后才会释放
    
    obj1.result()
    obj2.result() #拿到结果 # ThreadPoolExecuor,ProcessPoolExecutor都可以采用with statement with ThreadPoolExecutor(max_workers=1) as executor: obj1 = executor.submit(function, arg1, arg2) #提交子线程 obj2 = executor.map(func,iterator) #异步运行的map

    Others:

    •   obj.exception(timeout=second)   

      在second内如果没有结果就报错。 如果timeout=None 就相当于obj.join()无限制等待obj结束

    •   obj.add_done_callback(func)  

      将obj返回给func函数,由于返回的obj,所以func函数内需要obj.result()

    •   obj.cancel()

      如果被执行了,就返回false,如果在执行可以被cancel 就返回true

    •   obj.cancelled

      如果被cancel成功了就返回true

    •   done()

      没有在执行就返回true(被cancel或者运行完毕)

    exmaples:

    def wait_on_future():
        f = executor.submit(pow, 5, 2)
        # This will never complete because there is only one worker thread and
        # it is executing this function.
        print(f.result())
    
    executor = ThreadPoolExecutor(max_workers=1)
    executor.submit(wait_on_future)

    reference:  http://pythonhosted.org/futures/

  • 相关阅读:
    Codeforces 787D. Legacy 线段树优化建图+最短路
    Codeforces 1051E. Vasya and Big Integers
    BZOJ3261 最大异或和
    BZOJ3531 SDOI2014 旅行
    洛谷P2468 SDOI 2010 粟粟的书架
    2018 ICPC 焦作网络赛 E.Jiu Yuan Wants to Eat
    HDU6280 From Tree to Graph
    HDU5985 Lucky Coins 概率dp
    (HDU)1334 -- Perfect Cubes (完美立方)
    (HDU)1330 -- Deck (覆盖物)
  • 原文地址:https://www.cnblogs.com/yxi-liu/p/7677415.html
Copyright © 2011-2022 走看看