Skip to content

Instantly share code, notes, and snippets.

@olliemath
Created October 25, 2021 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olliemath/e11026501acc058f9ddeb7d6b32bd811 to your computer and use it in GitHub Desktop.
Save olliemath/e11026501acc058f9ddeb7d6b32bd811 to your computer and use it in GitHub Desktop.
Race condition
# 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