Skip to content

Instantly share code, notes, and snippets.

@panchishin
Created April 20, 2018 21:05
Show Gist options
  • Save panchishin/fe4a3b7c3820c71e73eb4406010b0761 to your computer and use it in GitHub Desktop.
Save panchishin/fe4a3b7c3820c71e73eb4406010b0761 to your computer and use it in GitHub Desktop.
Bare bones example of sharing a dictionary
"""
copied from https://docs.python.org/2.7/library/multiprocessing.html#sharing-state-between-processes
"""
from multiprocessing import Process, Manager
def f(d):
d[1] = '1'
d[0.25] = None
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
p = Process(target=f, args=(d,))
p.start()
p.join()
print d
"""
--- output ---
{0.25: None, 1: '1'}
"""
@panchishin
Copy link
Author

and it works with multiple instances of manager()

from multiprocessing import Process, Manager

def f(d1,d2):
    d1[1] = '1'
    d1[0.25] = None
    d2['one fish'] = 'red'
    d2['two fish'] = 'blue'

if __name__ == '__main__':
    manager1 = Manager()
    manager2 = Manager()
    d1 = manager1.dict()
    d2 = manager2.dict()
    p = Process(target=f, args=(d1,d2))
    p.start()
    p.join()
    print d1
    print d2

produces

{0.25: None, 1: '1'}
{'two fish': 'blue', 'one fish': 'red'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment