【问题标题】:Pass different arguments to ThreadPool.apply_async() method in python将不同的参数传递给 python 中的 ThreadPool.apply_async() 方法
【发布时间】:2019-06-12 11:56:25
【问题描述】:

我想将不同的参数传递给 ThreadPool.apply_async() 方法。我该怎么做?我以为是通过以下方式完成的,但我错了。 我可以改用 Thread 吗? 提前谢谢你

#!/usr/bin/env python
import multiprocessing

def testMethod(arg1, arg2, arg3):
    print(f"{arg1} - {arg2} - {arg3}"

if __name__ == '__main__':
    pool = multiprocessing.Pool()
    for t in range(1000):
        pool.apply_async(testMethod, t, arg2, arg3)

【问题讨论】:

    标签: python multithreading arguments threadpool pool


    【解决方案1】:

    typeshed 中方法签名的类型提示表明,后置参数必须作为可迭代对象提供:

    def apply_async(self,
                    func: (...) -> _T,
                    args: Iterable = ...,
                    kwds: Mapping[str, Any] = ...,
                    callback: Optional[(_T) -> None] = ...,
                    error_callback: Optional[(BaseException) -> None] = ...)
    

    您对apply_async 的调用应如下所示:

    pool.apply_async(testMethod, args=(t, 'foo', 'bar'))
    

    或者,使用关键字参数映射:

    pool.apply_async(testMethod, kwds={'arg1': t, 'arg2': 'foo', 'arg3': 'bar'})
    

    顺便说一句:您的代码示例不使用线程池; multiprocessing.Pool 是一个代表进程池的类,也就是说,它创建了单独的进程来充当工人。
    如果你想使用线程池,去:

    from multiprocessing.pool import ThreadPool
    pool = ThreadPool()
    

    界面类似于进程池。

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 2014-03-08
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多