from __future__ import with_statement import mutex, os, threading numthreads = 2 cond = threading.Condition() gotlock = [] failedlock = [] m = mutex.mutex() def runthread(threadnum): global gotlock, failedlock, m while True: print "Calling testandset in thread %d, m.locked is %s" % (threadnum, m.locked) x = m.testandset() if x: print "Thread %d locked" % threadnum with cond: if x: gotlock.append(threadnum) if len(gotlock) > 1: print "Hah, all these threads locked at the same time:", gotlock os._exit(1) else: failedlock.append(threadnum) if len(gotlock) + len(failedlock) == numthreads: print "Resetting, trying again" gotlock = [] failedlock = [] m.locked = False cond.notifyAll() else: cond.wait() threads = [threading.Thread(target = runthread, args = (i,)) for i in xrange(numthreads)] for thread in threads: thread.start() for thread in threads: thread.join()