【问题标题】:How to use python threadpool to execute none static function如何使用python线程池执行非静态函数
【发布时间】:2018-04-10 01:39:49
【问题描述】:

我是多线程的新手。我在网上浏览了一些文档。我注意到示例使用静态函数作为线程池输入。比如,

def task(n):
    time.sleep(3)
    print("Processing {}".format(n))

def main():

    print("Starting ThreadPoolExecutor")
    with ThreadPoolExecutor(max_workers=3) as executor:

        future = executor.submit(task,(2))
        future = executor.submit(task,(3))
        future = executor.submit(task,(4))
        future = executor.submit(task,(5))
        future = executor.submit(task,(6))
        future = executor.submit(task,(7))
        future = executor.submit(task,(8))
        future = executor.submit(task,(9))
        future = executor.submit(task,(10))

以上示例运行良好。任务并行执行

但是,如果我使用这样的实例中的函数

    class Test():
        def __init__(self, nums):
            self.nums = nums

        def test(self):

            print("Processing {}".format(str(self.nums)))
            time.sleep(3)

    def main():
        future = executor.submit(Test(2).test())
        future = executor.submit(Test(3).test())
        future = executor.submit(Test(4).test())
        future = executor.submit(Test(5).test())
        future = executor.submit(Test(6).test())
        future = executor.submit(Test(7).test())
        future = executor.submit(Test(8).test())
        future = executor.submit(Test(9).test())
        future = executor.submit(Test(10).test())

执行是顺序的,它会先执行sleep 3秒,然后执行第二个。它不再并行运行。

我尝试过 ThreadPoolExecutor、ProcessPoolExecutor、Pool,它们都执行相同,类实例中的函数不会并行执行。

在Java中,我们可以用线程池执行一个Runnable,像这样

Runnable worker = new WorkerThread("" + i);  
executor.execute(worker);

Python 是否有类似的 API 执行相同的操作?还是使用静态函数?

【问题讨论】:

  • 附带说明:(2) 不是一个值的元组,它只是不必要的括号内的数字 2。如果你真的想传递一个值的元组,你必须写(2,)。幸运的是,您不想在这里传递一个元组——submit 只需要 0 个或多个参数来传递给函数。
  • 另外,您的 Java 示例(假设 WorkerThread 不是一个具有严重误导性的名称)正在使用线程池来创建一堆新的独立线程,这是对线程池的浪费。您想将 tasks(又名Runnables)而不是线程放在线程池中。就像在 Python 中一样,除了在 Python 中,您可以传递任何可调用对象。

标签: python multithreading python-2.7 threadpool python-multithreading


【解决方案1】:

比较你的两个例子:

    future = executor.submit(task,(2))
    future = executor.submit(Test(2).test())

第一个是传递函数和参数。

第二个是调用方法并传递结果。

你要做的是传递方法:

    future = executor.submit(Test(2).test)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2020-10-04
    • 2020-01-31
    • 1970-01-01
    相关资源
    最近更新 更多