Reputation: 5596
I want to have an array of threads[] such that if a thread is "free" or not working on any program then it will be assigned a new task.
Is there anyway to check if a thread in ruby is "free". Currently I used
if (threads[thread_id].nil? || !threads[thread_id].status)
# yes thread is free
But doesn't seem to be correct way, some thread still override working other.
Upvotes: 1
Views: 3697
Reputation: 21
threads.each.map {|t| t.alive?}.none?
returns true if all threads are dead
if you have something like this:
threads << Thread.new do
# do dome work ...
end
and you want to check if all threads are not alive (i.e. dead) you can always use this:
threads.each.map {|t| t.alive?}.none?
We are taking one by one thread from array and checking if it's alive. map method is creating array with true/false values (alive/dead). Finally none? method of enumerable should return true if all members are false (i.e. all threads are dead)
Upvotes: 2
Reputation: 6283
See the answer of Deadlock in ThreadPool for a working threadpool implementation.
With a thread pool, you can do something like this:
pool = ThreadPool.new(10) # up to 10 threads
email_addresses.each do |addr|
pool.process {send_mail_to addr}
end
ThreadPool#process will block if there are no free threads to complete the work, and continue when one is free.
There are also gems implementing a thread pool, like: http://rubygems.org/gems/work_queue
Upvotes: 1