【问题标题】:How to use concurrent.futures in Python如何在 Python 中使用 concurrent.futures
【发布时间】:2018-08-27 17:57:00
【问题描述】:

我正在努力让多线程在 Python 中工作。我有我想根据参数在 5 个线程上执行的函数。我还需要每个线程都相同的 2 个参数。这就是我所拥有的:

from concurrent.futures import ThreadPoolExecutor

def do_something_parallel(sameValue1, sameValue2, differentValue):
    print(str(sameValue1))        #same everytime
    print(str(sameValue2))        #same everytime
    print(str(differentValue))    #different

main(): 

    differentValues = ["1000ms", "100ms", "10ms", "20ms", "50ms"]

    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = [executor.submit(do_something_parallel, sameValue1, sameValue2, differentValue) for differentValue in differentValues]

但我不知道下一步该做什么

【问题讨论】:

    标签: python multithreading python-3.x python-multithreading concurrent.futures


    【解决方案1】:

    如果您不关心订单,您现在可以这样做:

    from concurrent.futures import as_completed
    
    # The rest of your code here
    
    for f in as_completed(futures):
        # Do what you want with f.result(), for example:
        print(f.result())
    

    否则,如果您关心顺序,使用ThreadPoolExecutor.mapfunctools.partial 来填充始终相同的参数可能是有意义的:

    from functools import partial
    
    # The rest of your code...
    
    with ThreadPoolExecutor(max_workers=5) as executor:
        results = executor.map(
            partial(do_something_parallel, sameValue1, sameValue2),
            differentValues
        ))
    

    【讨论】:

      猜你喜欢
      • 2011-09-24
      • 2021-02-28
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 2017-05-29
      • 2017-05-18
      相关资源
      最近更新 更多