a managers.dict()允许在过程中共享字典并执行线程安全操作。在我的情况下,每个协调器过程都使用m
元素创建共享dict,而n
工作过程读取到/从单个dict键读取。
managers.dict()
是否有一个单锁或 m
锁,一个锁一个?
除了共同的dict,当工人不必互相交流时,还有另一种方式与n
工人共享m
元素吗?
相关的python-manager-dict-is-ever-slow-comparpy-to-dict-dict
在一些尝试之后,我可以说每个经理人只有一个锁。这是证明这一点的代码:
import time
import multiprocessing as mp
def process_f(key, shared_dict):
values = [i for i in range(64 * 1024 * 1024)]
print "Writing {}...".format(key)
a = time.time()
shared_dict[key] = values
b = time.time()
print "released {} in {}ms".format(key, (b-a)*1000)
def main():
process_manager = mp.Manager()
n = 5
keys = [i for i in range(n)]
shared_dict = process_manager.dict({i: i * i for i in keys})
pool = mp.Pool(processes=n)
for i in range(n):
pool.apply_async(process_f, (keys[i], shared_dict))
time.sleep(20)
if __name__ == '__main__':
main()
输出:
Writing 4...
Writing 3...
Writing 1...
Writing 2...
Writing 0...
released 4 in 3542.7968502ms
released 0 in 4416.22900963ms
released 1 in 6247.48706818ms
released 2 in 7926.97191238ms
released 3 in 9973.71196747ms
Process finished with exit code 0
写作时间的增加显示正在发生的等待。