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.
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.
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.
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.
Just toggle "tree view" and you can view each puma-worker and the threads under that worker.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With