Do not use global, use Manager.dict :
from multiprocessing import Process, Lock, Manager
class multiprocessingExample():
def __init__(self):
self.m = Manager()
self.d = self.m.dict()
self.lock = Lock()
def proc(self, num):
with self.lock:
if (num in self.d):
self.d[num] = d[num] + 1
else:
self.d[num] = 1
print("P " + str(num) + ": " + str(self.d))
def main(self):
jobs = []
for i in range(0, 10):
if (i % 2 == 0):
p = Process(target=self.proc, args=(i,))
jobs.append(p)
for job in jobs:
job.start()
for job in jobs:
job.join()
print("All: " + str(self.d))
obj = multiprocessingExample()
obj.main()
Which will output something like:
P 0: {0: 1}
P 2: {0: 1, 2: 1}
P 4: {0: 1, 2: 1, 4: 1}
P 8: {0: 1, 8: 1, 2: 1, 4: 1}
P 6: {0: 1, 8: 1, 2: 1, 4: 1, 6: 1}
All: {0: 1, 8: 1, 2: 1, 4: 1, 6: 1}
source
share