""" Prove that this program will clobber state without a lock in place In later test versions of this program, locks are in place and assertions are used, rather than setting .clobbered to true. If those program's locks are not working, the assertions will fail. But to prove they could fail, this program checks that the .state was clobbered by multiple threads. See also: synchronized-state.cobra and lock-state.cobra """ use System.Threading class X const numThreads = 8 const numReps = 20 const minSleepMS = 1 const maxSleepMS = 20 shared var clobbered = false var _rand = Random() var state = 0 def delay Thread.sleep(_rand.next(.minSleepMS, .maxSleepMS)) def work for n in .numReps, .readAndWriteState def readAndWriteState # Change state from 0 to 1 and back to 0 # with assertions along the way. # The delays allow other threads to modify the shared state # if a proper lock is not in place by whatever means. .delay if .state <> 0, .clobbered = true .state = 1 .delay if .state <> 1, .clobbered = true .state = 0 .delay if .state <> 0, .clobbered = true def main threads = for i in .numThreads get Thread(ThreadStart(ref .work)) for t in threads, t.start for t in threads, t.join assert .clobbered