python-如何编写一个多线程函数以同时处理不同的任务?

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

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

但是,我很难定义do_in_parallel函数以采用每个具有多个参数的多个函数,这是我的尝试:

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)

如此使用它,并得到以下错误:

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

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

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

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等),因此该调用结构将无法正常工作.

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

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

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

转载注明原文:python-如何编写一个多线程函数以同时处理不同的任务? - 代码日志