Created
October 25, 2021 14:14
-
-
Save olliemath/e11026501acc058f9ddeb7d6b32bd811 to your computer and use it in GitHub Desktop.
Race condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The following almost immediately raises an assertion error under nogil | |
# Under cpython it completes all 1000 iterations no problem | |
from threading import Thread | |
import time | |
positions = [] | |
def race(n): | |
# Race to be the first worker thread to complete! | |
time.sleep(0.1) | |
positions.append(n) | |
# Assert that we're the last thing in the array | |
assert len(positions) == positions.index(n) + 1 | |
def go(): | |
positions.clear() | |
ts = [Thread(target=race, args=(n,)) for n in range(8)] | |
for t in ts: | |
t.start() | |
for t in ts: | |
t.join() | |
for k in range(1000): | |
if k % 100 == 0: | |
print(f"=== {k} tries ===") | |
go() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment