Skip to content

Commit 95c78e3

Browse files
committed
bounded semaphor
1 parent 996b711 commit 95c78e3

3 files changed

Lines changed: 67 additions & 0 deletions

File tree

File renamed without changes.

src/thread_semaphore.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Race condition
3+
Thread safe
4+
Dead lock
5+
atomic
6+
"""
7+
from threading import Thread, Semaphore, current_thread, BoundedSemaphore
8+
from time import sleep
9+
10+
num = 0 # shared resource
11+
lock_normal = Semaphore(value=2)
12+
# lock_bounded = BoundedSemaphore(value=2)
13+
14+
def add():
15+
global num
16+
with lock_normal:
17+
print(current_thread().getName())
18+
sleep(2)
19+
num += 1
20+
21+
22+
# def add():
23+
# global num
24+
# lock_normal.acquire()
25+
# print(current_thread().getName())
26+
# sleep(2)
27+
# num += 1
28+
# lock_normal.release()
29+
30+
31+
#
32+
# def add():
33+
# global num
34+
# lock_bounded.acquire()
35+
# print(current_thread().getName())
36+
# sleep(2)
37+
# num += 1
38+
# lock_bounded.release()
39+
40+
t1 = Thread(target=add)
41+
t2 = Thread(target=add)
42+
t3 = Thread(target=add)
43+
t4 = Thread(target=add)
44+
t5 = Thread(target=add)
45+
t6 = Thread(target=add)
46+
t7 = Thread(target=add)
47+
t8 = Thread(target=add)
48+
49+
t1.start()
50+
t2.start()
51+
t3.start()
52+
t4.start()
53+
t5.start()
54+
t6.start()
55+
t7.start()
56+
t8.start()
57+
58+
t1.join()
59+
t2.join()
60+
t3.join()
61+
t4.join()
62+
t5.join()
63+
t6.join()
64+
t7.join()
65+
t8.join()
66+
67+
print('Done . . . ')

0 commit comments

Comments
 (0)