Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count running threads in ruby server

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.

like image 807
Tom Andersen Avatar asked May 23 '12 23:05

Tom Andersen


People also ask

How do I see the number of threads running in Linux?

Method 1 – /proc This is the easiest way to see the thread count of any active process on a Linux machine. proc command exports text file of process and system hardware information, such as CPU, interrupts, memory, disk, etc. The above example is having one thread per process.

How many threads can be executed at a time Ruby?

Only one thread may load or unload at a time, and to do either, it must wait until no other threads are running application code.

What are threads and processes in Ruby?

Multi-threading is the most useful property of Ruby which allows concurrent programming of two or more parts of the program for maximizing the utilization of CPU. Each part of a program is called Thread. So, in other words, threads are lightweight processes within a process.

How do I check my Puma threads?

Just toggle "tree view" and you can view each puma-worker and the threads under that worker.


1 Answers

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
like image 106
Kashyap Avatar answered Nov 12 '22 10:11

Kashyap