55 lines
859 B
Python
55 lines
859 B
Python
|
import random
|
||
|
import threading
|
||
|
import time
|
||
|
|
||
|
import matplotlib.pyplot as plt
|
||
|
|
||
|
|
||
|
def add(wait=0.0):
|
||
|
global glob
|
||
|
|
||
|
tmp = glob
|
||
|
time.sleep(wait)
|
||
|
|
||
|
LOCK_console.acquire()
|
||
|
print(f"{tmp} <- {tmp + 1}")
|
||
|
LOCK_console.release()
|
||
|
|
||
|
results.append(tmp + 1)
|
||
|
glob = tmp + 1
|
||
|
|
||
|
|
||
|
glob = 0
|
||
|
n = 100
|
||
|
|
||
|
LOCK_console = threading.Lock()
|
||
|
LOCK_glob = threading.Lock()
|
||
|
|
||
|
threads = []
|
||
|
results = []
|
||
|
for i in range(n):
|
||
|
rnd = random.randint(0, 1) / random.randint(1, 100)
|
||
|
threads.append(threading.Thread(target=add, args=(rnd,)))
|
||
|
threads[i].start()
|
||
|
|
||
|
while len(threads) != 0:
|
||
|
thread = threads.pop()
|
||
|
thread.join()
|
||
|
|
||
|
fig, ax = plt.subplots()
|
||
|
ax.plot(
|
||
|
range(n),
|
||
|
results
|
||
|
)
|
||
|
|
||
|
ax.set(
|
||
|
xlabel="Thread",
|
||
|
ylabel="Value",
|
||
|
title="Race-Condition: Increment",
|
||
|
ylim=(0, 100)
|
||
|
)
|
||
|
ax.grid(True)
|
||
|
|
||
|
plt.show()
|
||
|
print(f"{0} + {n} = {n} =? {glob}")
|