Skip to content

Commit 1660167

Browse files
committed
adding examples of race condition
1 parent abbb37b commit 1660167

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

content/example/race.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
2+
from multiprocessing import Value
3+
4+
# define a function to increment the value by 1
5+
def inc(i):
6+
val.value += 1
7+
8+
# using a large number to see the problem
9+
n = 100000
10+
11+
# create a shared data and initialize it to 0
12+
val = Value('i', 0)
13+
with ThreadPoolExecutor(max_workers=4) as pool:
14+
pool.map(inc, range(n))
15+
16+
print(val.value)
17+
18+
# create a shared data and initialize it to 0
19+
val = Value('i', 0)
20+
with ProcessPoolExecutor(max_workers=4) as pool:
21+
pool.map(inc, range(n))
22+
23+
print(val.value)

content/exercise/race_dup.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from concurrent.futures import ProcessPoolExecutor
2+
from multiprocessing import Array
3+
4+
5+
# define a function to increment the value by 1
6+
def inc(i):
7+
ind = mp.current_process().ident % 4
8+
arr[ind] += 1
9+
10+
# define a large number
11+
n = 100000
12+
13+
# create a shared data and initialize it to 0
14+
arr = Array('i', [0]*4)
15+
with ProcessPoolExecutor(max_workers=4) as pool:
16+
pool.map(inc, range(n))
17+
18+
print(arr[:],sum(arr))

content/exercise/race_lock.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
2+
from multiprocessing import Value, Lock
3+
4+
lock = Lock()
5+
6+
# adding lock
7+
def inc(i):
8+
lock.acquire()
9+
val.value += 1
10+
lock.release()
11+
12+
13+
# define a large number
14+
n = 100000
15+
16+
# create a shared data and initialize it to 0
17+
val = Value('i', 0)
18+
with ThreadPoolExecutor(max_workers=4) as pool:
19+
pool.map(inc, range(n))
20+
21+
print(val.value)
22+
23+
# create a shared data and initialize it to 0
24+
val = Value('i', 0)
25+
with ProcessPoolExecutor(max_workers=4) as pool:
26+
pool.map(inc, range(n))
27+
28+
print(val.value)

0 commit comments

Comments
 (0)