Something is wrong with my threads

Andy Jones <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <[email protected]>
Would any of you smart folks like to tell me what stupid thing I am doing here?

At this point I have a test program that just uses plain MRI, no gems.  If I keep running it, it will eventually fail (after a dozen runs at most).  Code at the end of this post.

What I'm doing is creating a lot of identical threads.  In each one I stop immediately, and then after the thread is re-entered, set a thread variable to say the thread is done then stop again.  I run them all, and then check they are all done.

The problem is, sometimes they aren't all done.  Which makes no sense to me.  Either `thread#run` sometimes doesn't wake a thread, or doesn't pass control to the thread; or something is wrong with thread variables?

Code:

require "time"

def make_thread(idx)
  Thread.new do
    # Set things up and wait
    Thread.current[:idx] = idx
    Thread.stop

    # do the work, then say we're done
    Thread.current[:done] = true
    Thread.stop
  end
end


threads = []; 1.upto(200){|i| threads << make_thread(i) }
starttm = Time.now

# Do the work
threads.each{|t| t.run }

# Wait until all work is done or we time out
sleep 0.1 until (threads.all?{|t| t[:done] } || Time.now >= starttm + 10)

# If all work is not done, something has gone very wrong?
fails = threads.reject{|t| t[:done] }
if fails.size > 0
  puts "FAIL"
  fails.each{|e| puts "#{e[:idx]}: #{e.alive?}" }
end




Click here to view Company Information and Confidentiality Notice.<http://www.jameshall.co.uk/index.php/small-print/email-disclaimer>

Please note that we have updated our privacy policy in line with new data protection regulations. Please refer to our website to view the ways in which we handle your data.


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.