Skip to content

Commit 0971e95

Browse files
committed
thread safe / dead lock / atomic
1 parent 021063b commit 0971e95

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed

src/multiple_thread_show.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
Thread Pool Executor
3+
4+
"""
5+
6+
from time import sleep, perf_counter
7+
from concurrent.futures import ThreadPoolExecutor
8+
from threading import Thread
9+
10+
11+
def show(name):
12+
print(f'Starting {name} ...')
13+
sleep(3)
14+
print(f'Finishing {name} ...')
15+
16+
17+
# with ThreadPoolExecutor() as executor:
18+
# names = ['One', 'Two', 'Three', 'Four', 'Five']
19+
# executor.map(show, names)
20+
21+
22+
with ThreadPoolExecutor(max_workers=2) as executor:
23+
names = ['One', 'Two', 'Three', 'Four', 'Five']
24+
executor.map(show, names)
25+
26+
print("Done . . .")

src/threat_lock_safe.py

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

0 commit comments

Comments
 (0)