1. 程式人生 > >Python 程序間共享變數(多程序通訊安全)

Python 程序間共享變數(多程序通訊安全)

import multiprocessing
import time


def worker(d, key, value):
    d[key] = value


if __name__ == '__main__':
    mgr = multiprocessing.Manager()
    d = mgr.dict()
    jobs = [multiprocessing.Process(target=worker, args=(d, i, i * 2))
            for i in range(10)
            ]
    for j in jobs:
        j.start()
    for j in jobs:
        j.join()
    print('Results:')
    print(dict(d))

[列印結果]:Results: {1: 2, 6: 12, 3: 6, 0: 0, 2: 4, 4: 8, 5: 10, 7: 14, 8: 16, 9: 18}