如何编写并发处理不同任务的多线程函数? [英] How to write a multithreaded function for processing different tasks concurrently?

查看:24
本文介绍了如何编写并发处理不同任务的多线程函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python 中定义一个 do_in_parallel 函数,它将接收带参数的函数,为每个函数创建一个线程并并行执行它们.该函数应该这样工作:

I would like to define a do_in_parallel function in python that will take in functions with arguments, make a thread for each and perform them in parallel. The function should work as so:

do_in_parallel(_sleep(3), _sleep(8), _sleep(3))

然而,我很难定义 do_in_parallel 函数来接受多个函数,每个函数都有多个参数,这是我的尝试:

I am however having a hard time defining the do_in_parallel function to take multiple functions with multiple arguments each, here's my attempt:

from time import sleep
import threading

def do_in_parallel(*kwargs):

    tasks = []

    for func in kwargs.keys():
        t = threading.Thread(target=func, args=(arg for arg in kwargs[func]))
        t.start()
        tasks.append(t)

    for task in tasks:        
        task.join()

def _sleep(n):
    sleep(n)
    print('slept', n)

照样使用,出现以下错误:

Using it as so, and getting the following error:

do_in_parallel(_sleep=3, _sleep=8, _sleep=3)

>> do_in_parallel(sleepX=3, sleepX=8, sleepX=3)
                            ^
>> SyntaxError: keyword argument repeated

有人可以解释一下我需要在我的函数中进行哪些更改,以便它可以采用多个函数参数:

Can someone explain what I would need to change in my function so that it can take multiple function parameters as so:

do_in_parallel(_sleep(3), _sleep(8), maybe_do_something(else, and_else))

推荐答案

do_in_parallel(_sleep(3), _sleep(8),maybe_do_something(else, and_else))

此调用结构无论如何都不起作用,因为您将目标函数的结果传递给 do_in_parallel(您已经在调用 _sleep 等).

This call structure wouldn't work anyway since you are passing the results of your target functions to do_in_parallel (you are already calling _sleep etc.).

相反,您需要做的是捆绑任务并将这些任务传递给您的处理功能.这里的任务是一个元组,包含要调用的目标函数和一个参数元组 task = (_sleep, (n,)).

What you need to do instead, is bundle up tasks and pass these tasks to your processing function. A task here is a tuple, containing the target function to be called and an argument-tuple task = (_sleep, (n,)).

我建议您然后使用 ThreadPool 和 apply_async 方法来处理单独的任务.

I suggest you then use a ThreadPool and the apply_async method to process the separate tasks.

from time import sleep
from multiprocessing.dummy import Pool  # .dummy.Pool is a ThreadPool


def _sleep(n):
    sleep(n)
    result = f'slept {n}'
    print(result)
    return result


def _add(a, b):
    result = a + b
    print(result)
    return result


def do_threaded(tasks):
    with Pool(len(tasks)) as pool:
        results = [pool.apply_async(*t) for t in tasks]
        results = [res.get() for res in results]
    return results


if __name__ == '__main__':

    tasks = [(_sleep, (i,)) for i in [3, 8, 3]]
    # [(<function _sleep at 0x7f035f844ea0>, (3,)),
    #  (<function _sleep at 0x7f035f844ea0>, (8,)),
    #  (<function _sleep at 0x7f035f844ea0>, (3,))]
    tasks += [(_add, (a, b)) for a, b in zip(range(0, 3), range(10, 13))]

    print(do_threaded(tasks))

输出:

10
12
14
slept 3
slept 3
slept 8
['slept 3', 'slept 8', 'slept 3', 10, 12, 14]

Process finished with exit code 0

这篇关于如何编写并发处理不同任务的多线程函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆