From: Justin Collins Date: 2008-03-07T09:51:58+09:00 Subject: Re: Threading weirdness Philip Scott wrote: > Hi guys, > > ######################################## PROGRAM 2: DOESNT WORK, > TERMINATES > require 'thread' > require 'digest/md5' > > a = [] > b = [] > > # Fill two identical arrays full of 10 random strings > for i in (0..9) > a[i] = Digest::MD5.hexdigest(rand(1000).to_s).to_s > b[i] = a[i] > end > > print "Starting threads\n" > Thread.abort_on_exception = true > > # Start a hundred threads reading items from the two arrays and > comparing them > for x in (0..100) > testThread = Thread.new do > while true > i = rand(9) > if (a[i] != b[i]) > raise Exception.new("Threading Broke") > end > end > end > end > > print "And we're off" > > # Spin forever (or at least until an Exception gets thrown) > while true do > end > The variable 'i' is shared across all threads because it was created when you initialized the arrays and is still in scope when you create the threads. -Justin