为什么?多处理.池无法更改全局变量?

2024-04-24 00:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用multiprocessing.Pool加载一个大型数据集,下面是我使用的代码:

import os
from os import listdir
import pickle
from os.path import join
import multiprocessing as mp

db_path = db_path
the_files = listdir(db_path)
fp_dict = {}
def loader(the_hash):
        global fp_dict
        the_file = join(db_path, the_hash)
        with open(the_file, 'rb') as source:
                fp_dict[the_hash] = pickle.load(source)
        print(len(fp_dict))
def parallel(the_func, the_args):
        global fp_dict
        pool = mp.Pool(mp.cpu_count())
        pool.map(the_func, the_args)
        print(len(fp_dict))
parallel(loader, the_files)

有趣的是,fp_dict的长度在代码运行时发生变化。但是,只要进程终止,fp_dict的长度就为零。为什么?如何使用multiprocessing.Pool修改全局变量?在


Tags: thepathfromimportdbosmphash
1条回答
网友
1楼 · 发布于 2024-04-24 00:26:21

因为您正在使用multiprocessing.Pool,所以您的程序在多个进程中运行。每个流程都有自己的全局变量副本,每个流程都会修改自己的全局变量副本,工作完成后,每个流程都会终止。主进程从未修改其全局变量的副本。在

如果要收集有关每个工作进程内部发生的事情的信息,应该使用.map()方法函数,并从每个工作进程返回一个数据元组。然后让主程序收集元组并从数据中整理出一个字典。在

下面是一个YouTube教程,它使用multiprocessing.Pool().map()来收集工作函数的输出。在

https://www.youtube.com/watch?v=_1ZwkCY9wxk

这是我为StackOverflow编写的另一个答案,它展示了如何传递元组,以便worker函数可以接受多个参数;以及如何从worker函数返回一个包含多个值的元组。它甚至可以根据返回的值生成字典。在

https://stackoverflow.com/a/11025090/166949

相关问题 更多 >