From: Aldric Giacomoni Date: 2009-12-16T23:14:55+09:00 Subject: Re: Using threads to show progress Brian Candler wrote: > Piyush Ranjan wrote: >> In the enumerate thread keep pushing id to queue whenever there is a new >> object being worked on. >> >> dictated_exams.each do |exam| >> queue.push exam.id >> end > > That's a really good suggestion: the consumer will block when it tries > to pop from the queue, so you don't need to spin. > The idea of the queue is very good. I now have this code going for me : require 'thread' queue = Queue.new dictated_exams = (1..1_000_000) backspaces = 8 # Max of dictated_exams string size worker_thread = Thread.new do dictated_exams.each do |exam| queue << exam end end consumer_thread = Thread.new do while true id = queue.pop print "\b" * backspaces print id end end worker_thread.join consumer_thread.kill As someone noticed, I am new to threads (I didn't think it was written on my forehead, but I guess it must be next to the "Kick me" sign on my back). I'm looking for a way to have an idea of what long rake tasks are doing. I wrote a long and convoluted task to find and delete rows which contain duplicate data. While I am working on it and polishing it up, I'd like to be able to keep track of what it does. It has a couple of 'each' statements, so I will probably end up needing to call a 'printing' thread a few times, once for each step -- that is why I can't just use the main thread to print.. And this also gave me the idea of trying my hand at writing a simple gem or plugin to indicate progress (I know it's been done before, but it may be good practice for me). David said that threads aren't elegant. I somewhat agree, I don't really like working with them, they seem clunky right now, but it seems to be a pretty good way to separate the "showing progress" code and the "getting work done" code. Are there better ways to do this? My original reason for wanting this, which may be misguided, was the cost in time for doing a "print" - I remember my early days with Ruby, working on Project Euler and trying to keep track of how fast my brute-force solutions were going.. And they went MUCH faster without a "put" in the loop. -- Posted via http://www.ruby-forum.com/.