1
+ import time
2
+ import multiprocessing
3
+
4
+ def deposit (balance ):
5
+ for i in range (100 ):
6
+ time .sleep (0.01 )
7
+ balance .value = balance .value + 1
8
+
9
+
10
+ def withdraw (balance ):
11
+ for i in range (100 ):
12
+ time .sleep (0.01 )
13
+ balance .value = balance .value - 1
14
+
15
+ def problem ():
16
+ balance = multiprocessing .Value ('i' , 200 )
17
+ d = multiprocessing .Process (target = deposit , args = (balance , ))
18
+ w = multiprocessing .Process (target = withdraw , args = (balance , ))
19
+
20
+ d .start ()
21
+ w .start ()
22
+
23
+ d .join ()
24
+ w .join ()
25
+ # it should print 200 but it does not
26
+ print ("After transactions: " , balance .value )
27
+
28
+
29
+ def deposit_solution (balance , lock ):
30
+ for i in range (100 ):
31
+ time .sleep (0.01 )
32
+ lock .acquire ()
33
+ balance .value = balance .value + 1
34
+ lock .release ()
35
+
36
+
37
+ def withdraw_solution (balance , lock ):
38
+ for i in range (100 ):
39
+ time .sleep (0.01 )
40
+ lock .acquire ()
41
+ balance .value = balance .value - 1
42
+ lock .release ()
43
+
44
+
45
+ def solution ():
46
+ balance = multiprocessing .Value ('i' , 200 )
47
+ lock = multiprocessing .Lock ()
48
+ d = multiprocessing .Process (target = deposit_solution , args = (balance , lock ))
49
+ w = multiprocessing .Process (target = withdraw_solution , args = (balance , lock ))
50
+
51
+ d .start ()
52
+ w .start ()
53
+
54
+ d .join ()
55
+ w .join ()
56
+ # it should print 200 but it does not
57
+ print ("After transactions: " , balance .value )
58
+
59
+ if __name__ == '__main__' :
60
+ problem ()
61
+ solution ()
0 commit comments