From: David Masover Date: 2009-12-16T10:36:57+09:00 Subject: Re: Using threads to show progress On Tuesday 15 December 2009 01:53:21 pm Aldric Giacomoni wrote: > Aldric Giacomoni wrote: > > I want to do this in a Rake task, but the concept is Ruby. I would like > > to use one thread to do the work, and one thread to periodically tell me > > "We're working on element x now". I'm trying to work from this page: > > http://ruby-doc.org/docs/ProgrammingRuby/html/tut_threads.html > > Here is basically what I have: > > I've successfully implemented it this way: [snip] > Thread.current[:id] = exam.id What's the advantage of making this a thread-local variable? Taking Brian Candler's advice into account, I'd probably do this: desc "Go through dictated exams and show IDs" task(:showSomeIDs => :environment) do dictated_exams = DictatedExam.all current_id = nil enumerate = Thread.new do dictated_exams.each do |exam| current_id = exam.id end end while enumerate.alive? sleep 0.01 puts current_id end enumerate.join end In this case, it's simple enough that doing the threading yourself isn't too bad. But since you seem new to threading, here's a couple things we didn't cover: - Locking. In this case, you're only printing the value of one variable which I assume is an integer, so updates to that should be atomic. You'll probably be fine if you're just printing some status, but you never know -- even methods that don't have ! on them can modify state. - Exception handling. Actually, I did that by joining the thread anyway, even though I know it's ended when the loop is over. If I didn't do that, any exceptions raised within the thread would be silently ignored. Threads really aren't elegant. They are the 'goto's of concurrency, and I don't know of anyone who actually claims that naked threads are the way forward. The only way this would be elegant is if it was hidden away in a library which exposed a higher-level interface to the user -- but I'm not sure something like that exists or would be useful here.