How to count running threads in ruby server

multithreading, ruby, sinatra

Solution

This will give the count of threads that are having the status of "run" and not "sleep"

def running_thread_count
  Thread.list.select {|thread| thread.status == "run"}.count
end

Problem

I want to do a 'long running' - (takes about 0.5 seconds to execute) task in a thread in a Sinatra web server. The web response takes about 20 ms, so if I get busy then threads will pile up... So I was thinking that I would do it synch if I get busy.. ``` if (running_thread_count > 10) stuff_that_takes_a_second() else Thread.new do stuff_that_takes_a_second() end end ``` How do you get the number of running threads (I want the the number of threads launched, and not done running yet) - how do you code running_thread_count? ``` def running_thread_count return Thread.list.count end ``` Or do I need to check for threads that are running? i.e. when a thread is finished running, will it stop coming back in the Thread.list? I don't want to call join as that would defeat the purpose - which is to return quickly unless we are backed up with lots of threads working.

Original source