forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.py
More file actions
28 lines (19 loc) · 597 Bytes
/
shared.py
File metadata and controls
28 lines (19 loc) · 597 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import multiprocessing
lock = multiprocessing.Lock()
class Process(multiprocessing.Process):
def __init__(self, counter):
super(Process, self).__init__()
self.counter = counter
def run(self):
for i in range(1000):
with lock:
self.counter.value += 1
def main():
counter = multiprocessing.Value('i', lock=True)
counter.value = 0
processes = [Process(counter) for i in range(4)]
[p.start() for p in processes]
[p.join() for p in processes]
print(counter.value)
if __name__ == '__main__':
main()