首页 > 解决方案 > Python中的简单并行过程

问题描述

我有一个(非常)简单的过程可以多次执行,大致如下:

import time

class Shop:
    def __init__(self):
        time.sleep(1.)
        self.sale_price = 0
    def update(self, weight, price):
        self.sale_price = weight * price
        
my_list = [Shop() for _ in range(20)]  #20 shops

weight, price = 2, 3

for o in my_list:
    o.update(weight, price)

(函数update改变 的内部状态o,没有任何返回值)

我的问题:让这个循​​环/进程并行运行的简单方法是什么?

我在这里看到了许多并行数学运算(例如矩阵运算)的示例,但我无法让它们适用于我的简单示例。我正在使用 Python 3.6.5

标签: pythonparallel-processing

解决方案


找到了一个简单的解决方案:

import time
from joblib import Parallel, delayed
import multiprocessing

class Shop:
    def __init__(self):
        time.sleep(1.)
        self.sale_price = 0
    def update(self, weight, price):
        self.sale_price = weight * price
        
my_list = [Shop() for _ in range(20)]  #20 shops
weight, price = 2, 3



### Non-parallel
for o in my_list:
    o.update(weight, price)



### Parallel
#Helper function (doesn't take weight/price parameters - assumes these are already defined)
def update2(o):
    o.update(weight, price)
    return o
num_cores = multiprocessing.cpu_count()
my_list = Parallel(n_jobs=num_cores)(delayed(update2)(o) for o in my_list)

我意识到这my_list最终会重新分配,但这对我的目的来说很好。


推荐阅读