开发者

Ruby check if a thread is "free"

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.


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜