A managers.dict()允许跨进程共享字典并执行线程安全操作。
在我的情况下,每个协调器进程创建共享的dict,其中m
个元素和n
个工作进程读取和写入单个dict键。
对于dict或managers.dict()
锁定,m
只有一个锁,其中每个锁对应一个锁吗?
当工人不需要彼此沟通时,是否有另一种方法可以将m
元素分享给n
工作人员,而不是共享字典?
答案 0 :(得分:1)
经过一些尝试,我可以说每个经理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
越来越多的写作时间显示正在发生的等待。