Skip to content

Commit e1e514f

Browse files
committed
start ch2.7
1 parent c0e4ae4 commit e1e514f

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
使用RLock进行线程同步
22
=====================
3+
4+

chapter2/box.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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)

0 commit comments

Comments
 (0)