具有不同功能的多进程池
多进程工作池的大多数示例在不同进程中执行单个函数,有
def foo(args):
pass
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=30)
res=pool.map_async(foo,args)
没有办法在池中处理两个不同且独立的函数?这样您就可以为 foo() 分配 15 个进程,为 bar() 分配 15 个进程,还是一个池仅限于单个函数?或者您必须手动为不同的功能创建不同的进程
p = Process(target=foo, args=(whatever,))
q = Process(target=bar, args=(whatever,))
q.start()
p.start()
并忘记工作池?
Most examples of the Multiprocess Worker Pools execute a single function in different processes, f.e.
def foo(args):
pass
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=30)
res=pool.map_async(foo,args)
Is there a way to handle two different and independent functions within the pool? So that you could assign f.e. 15 processes for foo() and 15 processes for bar() or is a pool bounded to a single function? Or du you have to create different processes for different functions manually with
p = Process(target=foo, args=(whatever,))
q = Process(target=bar, args=(whatever,))
q.start()
p.start()
and forget about the worker pool?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要传递不同的函数,您只需多次调用
map_async
即可。这是一个例子来说明,
结果将是:
To pass different functions, you can simply call
map_async
multiple times.Here is an example to illustrate that,
The result will be:
您可以使用map或某些lambda函数(编辑:实际上您不能使用lambda函数)。您可以使用一个简单的映射函数:
普通的map函数将iterables作为输入,这很不方便。
You can use map or some lambda function (edit: actually you can't use a lambda function). You can use a simple map function:
The normal map function takes iterables as inputs, which is inconvenient.
这是@Rayamon 分享的想法的一个有效示例:
Here is a working example of the idea shared by @Rayamon:
它们不会并行运行。
请参阅以下代码:
上面的代码产生以下打印输出:
They will not run in parallel.
See following code:
The above code yields the following printout:
一个池中的多个函数
以下示例演示如何在池中运行
inc
、dec
和add
三个函数。我们有三个函数,它们在池中独立运行。我们使用 functools.partial 在执行之前准备函数及其参数。
来源:https://zetcode.com/python/multiprocessing/
Multiple Functions in one Pool
The following example shows how to run the three functions
inc
,dec
, andadd
in a pool.We have three functions, which are run independently in a pool. We use the functools.partial to prepare the functions and their parameters before they are executed.
Source: https://zetcode.com/python/multiprocessing/
为了进一步解释上面的其他答案,这里有一个示例:
To further explain the other answer above, here is an example of: