【问题标题】:How to pass a thread object to the ThreadPoolExecutor?如何将线程对象传递给 ThreadPoolExecutor?
【发布时间】:2020-01-01 20:37:26
【问题描述】:

concurrent.futures.ThreadPoolExecutor 用于函数 传递给带有executor.submit(my_function) 的执行器,如下所示:

def my_function():
    print("Hello, world!")

with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
    for t in range(50):
        executor.submit(my_function())

但是有没有办法传递一个线程对象来代替?我有一个线程子类,我想与执行器一起使用。

【问题讨论】:

标签: python multithreading concurrent.futures


【解决方案1】:

试试这样的:

import concurrent.futures

def my_function(num_time):
    print(f"Hello, world {num_time} times")

with concurrent.futures.ThreadPoolExecutor() as executor:
    
    results = [executor.submit(my_function,i) for i in range(50)]
  

    for f in concurrent.futures.as_completed(results):
        print(f.result())

【讨论】:

  • A code-only answer is not high quality。虽然此代码可能很有用,但您可以通过说明其工作原理、工作方式、何时应该使用以及它的局限性来改进它。请edit您的回答包括解释和相关文档的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多