【发布时间】:2018-03-11 10:32:01
【问题描述】:
我在 python3 中的代码有一个问题: 我尝试了许多解决方案,但结果仍然相同。
import pprint
import concurrent
import multiprocessing
from concurrent import futures
class exempleStackOverFlow:
def __init__(self):
self.dict1={}
self.headers = {"header1","header2","header3"}
def fillIn(self,key):
response = {key:{'first':['1','2','3']}}
self.dict1.update(response)
pprint.pprint(response)
e = exempleStackOverFlow()
def try_my_operation(item):
try:
e.fillIn(item)
except:
print('error with item')
executor = concurrent.futures.ProcessPoolExecutor(2)
futures = [executor.submit(try_my_operation, item) for item in e.headers]
concurrent.futures.wait(futures)
print(e.dict1)
结果
{'header3': {'first': ['1', '2', '3']}}
{'header1': {'first': ['1', '2', '3']}}
{'header2': {'first': ['1', '2', '3']}}
{}
预期
{'header3': {'first': ['1', '2', '3']}}
{'header1': {'first': ['1', '2', '3']}}
{'header2': {'first': ['1', '2', '3']}}
{'header1': {'first': ['1', '2', '3']},
'header2': {'first': ['1', '2', '3']},
'header3': {'first': ['1', '2', '3']}}
(或任何标题的顺序)
我可能不明白这是如何工作的,我想了解一下我的问题,当我输入时,dict1 最后是空的
try_my_operation.
在没有多处理/并发的情况下它确实可以很好地更新(就像我这样做 e.fillIn("headers1"),e.fillIn("headers2")... 并且在我可以让 dict1 充满之后。
感谢您以后的任何 cmets
【问题讨论】:
-
您正在一个主进程之上创建 2 个进程。您的结果是您的代码所期望的。得到你当前的结果加上打印所有三个从
self.dict1.update附加在一起的想法? -
感谢您的回答,这只是打印到跟踪更改的结果。在结果中,我返回的 dict 为空 {} 而不是我在“预期”中想要的,这意味着
self.dict1 equal to {'header1': {'first': ['1', '2', '3']}, 'header2': {'first': ['1', '2', '3']}, 'header3': {'first': ['1', '2', '3']}}而不是 self.dict1 等于 {} -
在下面查看我的答案
标签: python-3.x function dictionary concurrency python-multiprocessing