各位大佬好,我在使用python多进程的时候遇到了一个问题
def multi_process():
# with ProcessPoolExecutor() as pool:
# pool = mp.Pool(mp.cpu_count())
with mp.Pool() as pool:
pool.starmap(ISC, [(l, t) for l in range(2 * brCount) for t in range(Time)])
if __name__ == "__main__":
for_start = time.time()
multi_process()
for_end = time.time()
函数ISC定义为:
def ISC(l, t):
global ISCR_C
ISCR_C[:, 0] = ISCR_A[l, :]
ISCR_C[:, 1] = ISCR_Pmax
ISCR_C = ISCR_C[np.lexsort(-ISCR_C[:, ::-1].T)]
if l <= brCount - 1:
for k in range(GenCount - 1):
if ISCR1(k, t) * ISCR2(k, t) * ISCR3(l, k, t) == 1:
opt.remove_constraint(model.branch_Cap1[t, l])
break
else:
for k in range(GenCount - 1):
if ISCR1(k, t) * ISCR2(k, t) * ISCR3(l, k, t) == 1:
opt.remove_constraint(model.branch_Cap2[t,l - brCount])
break
程序运行会报错:
第一次用多进程,除了问题也不知咋回事,有没有大佬能救救孩子
2021.12.21更新
问题好像解决了,python多进程使用的multiprocessing包默认使用pickle,但是pickle无法处理lambda、闭包之类的东西,把multiprocessing包换成multiprocessing_on_dill问题就解决了,更新后的程序大概是这样的:
# 调用multiprocessing_on_dill包
from multiprocessing_on_dill.dummy import Pool
# %% 主程序部分
def multi_process():
with Pool() as pool:
pool.starmap(ISC, [(l, t) for l in range(2 * brCount) for t in range(Time)])
if __name__ == "__main__":
for_start = time.time()
multi_process()
for_end = time.time()
for_caltime = (for_caltime + for_end - for_start) / (testtimes + 1)