我试图通过传递Manager.dict来捕捉每个进程的开始和结束时间。当我使用 趣味 它不像预期的那样工作,但对于 fun_1 它的工作。我在python 3.7 (IDE VS Code)上运行这段代码。
import time
from multiprocessing import Manager
from multiprocessing.pool import Pool
def fun(a, d):
if a not in d:
d[a] = list()
d[a].append(time.time())
time.sleep(1)
d[a].append(time.time())
def fun_1(a, d):
s = time.time()
time.sleep(1)
e = time.time()
d[a] = [s, e]
if __name__ == '__main__':
pool = Pool(4)
m = Manager()
d = m.dict()
pool.starmap(fun, [(i, d) for i in range(10)])
print(d) # {3: [], 0: [], 2: [], 1: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}
看来我好像遗漏了什么。先谢谢你
这个帖子解释了你的问题。https:/bugs.python.orgissue36119
解决这个问题的方法是,你应该执行一次 __setitem__
操作,让系统注意到对象的变化,并将其传播到共享管理器对象。这就是为什么你的fun_1确实能像你的execute d[a] = [s,e]
.
另一个选择是,你可以预先定义 manager.list() 对象,而不是普通的 list 对象,在这种情况下,它应该以你期望的方式执行。