Skip to content

Instantly share code, notes, and snippets.

@rntz
Created May 14, 2015 00:12
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 rntz/36a2fb668a5d2bbe5b92 to your computer and use it in GitHub Desktop.
Save rntz/36a2fb668a5d2bbe5b92 to your computer and use it in GitHub Desktop.
Python bug
import subprocess
import threading
import sys
the_cvar = threading.Condition(threading.RLock())
turn = 0
NTHREADS = 20
WINDOW = 1
ITERS = 100
class Worker(object):
def __init__(self, id):
self.id = id
def fidget(self):
with the_cvar:
the_cvar.notifyAll()
def say(self, x):
for c in x:
sys.stdout.write(c)
self.fidget()
sys.stdout.write('\n')
sys.stdout.flush()
self.fidget()
def work(self):
global turn
for i in range(ITERS):
self.say('%sthread %s iteration %s\n' % (' ' * self.id, self.id, i))
while True:
with the_cvar:
if (self.id - turn) % NTHREADS <= WINDOW:
turn = (turn + 1) % NTHREADS
the_cvar.notifyAll()
break
# self.say('%sthread %s sleeping' % (' ' * self.id, self.id))
the_cvar.wait()
self.say("thread %s done" % (self.id,))
def worker(id):
Worker(id).work()
threads = []
for i in range(NTHREADS-1):
print 'starting thread %d' % (i+1)
t = threading.Thread(target=worker, args=(i+1,))
threads.append(t)
t.start()
print 'starting thread 0'
worker(0)
for t in threads:
t.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment