This is my first touch on threads, so be gentle pls
I am trying to execute loop a command by using threads (tested them on
windows and I find them much faster than doing one at a time :).
However, there are some commands that execuite very long time and are memory
intensive, so I want that I only execute 10 threads at a time.
eg.
LIMIT= 10
tlist = []
loop {
     if tlist.size< LIMIT
        tlist << Thread.new { p "test" }
     else
        sleep 5
     end
}
Am, I right? Of course, I'm wrong since I tested it; tlist size is steady at
LIMIT. When I view tlist, the threads are dead, so how do I shrink tlist
properly? Will the threads just go away if I delete any item in tlist and
compact tlist? Can anyone give some hints pls?
PARALLEL.times do
threads << Thread.new(queue) do |q|
until ( TERMINATOR == ( obj = q.deq ) )
# do something with obj
puts "#{Thread.current.inspect}: #{obj.inspect}"
# or maybe deal with arbitrary code
begin
obj.call if obj.respond_to? :call
rescue Exception => e
$stderr.puts e
end
end
end
end
(In response to news:20050124005127.F2A9982B3@mx2.delmonte-phil.com by
Peña, Botp)
LIMIT= 10
tlist =
tlist = ThreadGroup.new
loop {
if tlist.size< LIMIT
tlist << Thread.new { p "test" }
tlist.add Thread.new { p "test" }
else
sleep 5
end
}
ThreadGroups automatically drop Threads that are no longer alive. Use tlist.list to get the list of threads currently in the ThreadGroup.
I'd recommend discarding threads that are dead from the list like this:
tlist.select! { |t| t.alive? }
Threads may die between the time you pick them out and the time you decide to do something with them. You'll have to check each one in a critical section before doing some work that requires the thread to be alive, or rescue an exception around the operation.