File tree 2 files changed +56
-0
lines changed
2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 1
1
使用RLock进行线程同步
2
2
=====================
3
+
4
+
Original file line number Diff line number Diff line change
1
+ import threading
2
+ import time
3
+
4
+ class Box (object ):
5
+ lock = threading .RLock ()
6
+
7
+ def __init__ (self ):
8
+ self .total_items = 0
9
+
10
+ def execute (self , n ):
11
+ Box .lock .acquire ()
12
+ self .total_items += n
13
+ Box .lock .release ()
14
+
15
+ def add (self ):
16
+ Box .lock .acquire ()
17
+ self .execute (1 )
18
+ Box .lock .release ()
19
+
20
+ def remove (self ):
21
+ Box .lock .acquire ()
22
+ self .execute (- 1 )
23
+ Box .lock .release ()
24
+
25
+ ## These two functions run n in separate
26
+ ## threads and call the Box's methods
27
+ def adder (box , items ):
28
+ while items > 0 :
29
+ print ("adding 1 item in the box" )
30
+ box .add ()
31
+ time .sleep (5 )
32
+ items -= 1
33
+
34
+ def remover (box , items ):
35
+ while items > 0 :
36
+ print ("removing 1 item in the box" )
37
+ box .remove ()
38
+ time .sleep (5 )
39
+ items -= 1
40
+
41
+ ## the main program build some
42
+ ## threads and make sure it works
43
+ if __name__ == "__main__" :
44
+ items = 5
45
+ print ("putting %s items in the box " % items )
46
+ box = Box ()
47
+ t1 = threading .Thread (target = adder , args = (box , items ))
48
+ t2 = threading .Thread (target = remover , args = (box , items ))
49
+ t1 .start ()
50
+ t2 .start ()
51
+
52
+ t1 .join ()
53
+ t2 .join ()
54
+ print ("%s items still remain in the box " % box .total_items )
You can’t perform that action at this time.
0 commit comments