You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
859 B

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}")