You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用多线程创建类对象字典时得到空字典的问题求助

问题原因

你用的ProcessPoolExecutor是多进程实现,而不同进程拥有完全独立的内存空间。子进程里修改的this_dict只是主进程字典的一个副本,主进程的原字典不会被任何子进程改动,所以最终得到空字典。

解决方案

根据你的场景需求,有三种可行方案:

1. 改用线程池(ThreadPoolExecutor)

如果你的任务是IO密集型(比如网络请求、文件读写),直接换成线程池即可——线程共享同一进程的内存空间,修改的是同一个字典:

import concurrent.futures

this_dict = {}
item_list = ['a', 'b', 'c', 'e', 'f', 'g']

class Bot:
    def __init__(self): 
        self.value = 1

def create_bots(item):
    this_dict[item] = Bot()

if __name__ == '__main__':
    executor = concurrent.futures.ThreadPoolExecutor()
    futures = [executor.submit(create_bots, item) for item in item_list]
    concurrent.futures.wait(futures)
    print(this_dict)  # 此时字典已被正确填充

2. 使用进程间共享字典(适用于CPU密集型任务)

如果必须用多进程(比如需要利用多核算力的CPU密集型任务),可以用multiprocessing.Manager创建一个能在进程间共享的字典:

import concurrent.futures
from multiprocessing import Manager

item_list = ['a', 'b', 'c', 'e', 'f', 'g']

class Bot:
    def __init__(self): 
        self.value = 1

def create_bots(item, shared_dict):
    shared_dict[item] = Bot()

if __name__ == '__main__':
    with Manager() as manager:
        this_dict = manager.dict()
        executor = concurrent.futures.ProcessPoolExecutor()
        futures = [executor.submit(create_bots, item, this_dict) for item in item_list]
        concurrent.futures.wait(futures)
        # 可选:将共享字典转为普通字典
        result_dict = dict(this_dict)
        print(result_dict)

3. 收集子进程返回结果(更简洁的多进程方案)

让子进程直接返回key和对应的Bot对象,由主进程统一收集并填充字典:

import concurrent.futures

item_list = ['a', 'b', 'c', 'e', 'f', 'g']

class Bot:
    def __init__(self): 
        self.value = 1

def create_bots(item):
    return item, Bot()

if __name__ == '__main__':
    this_dict = {}
    executor = concurrent.futures.ProcessPoolExecutor()
    futures = [executor.submit(create_bots, item) for item in item_list]
    # 遍历完成的任务,收集结果
    for future in concurrent.futures.as_completed(futures):
        key, bot_obj = future.result()
        this_dict[key] = bot_obj
    print(this_dict)

内容的提问来源于stack exchange,提问作者Andy Visser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:17:11