我正在尝试创建类对象的字典。如果我一次做一个,它就会起作用。如果我尝试使用多线程,我最终会得到一个空字典。
这适用于一项:
import concurrent
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()
create_bots('test')
但是,如果我使用下面的例子,我最终会得到一个空字典。我该怎么做?
import concurrent
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.ProcessPoolExecutor(1)
futures = [executor.submit(create_bots, item) for item in item_list]
concurrent.futures.wait(futures)
找到它,大概花了 6 个小时试图弄明白,提出问题然后偶然发现了一篇文章。下面替换现有的 PoolExecutor.
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(create_bots, item) for item in item_list]
concurrent.futures.wait(futures)