4

manager.dict ()允许跨进程共享字典并执行线程安全操作。在我的情况下,每个协调器进程都创建共享字典,其中包含m元素和n工作进程读取和写入单个字典键。

字典是否managers.dict()有一个m锁,每个锁一个锁?

当工人不必相互交流时,除了共享字典之外,还有其他方法可以m向工人共享元素吗?n

相关的 python-manager-dict-is-very-slow-compared-to-regular-dict

4

1 回答 1

6

经过一些尝试,我可以说每个经理的字典只有一个锁。这是证明它的代码:

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

写作时间的增加表明正在发生的等待。

于 2017-12-18T19:56:23.490 回答