To perform actions that enqueued into Worker and do not take all CPU resources we need to do arrange dequeued algorithm in a smart way.

queue = Queue.new loop do

puts "we need dequeue actions and do some job" unless queue.empty?

end

A loop like above will eat all free CPU time.

Here is the output of top command when the loop is running:

$ top -o cpu PID COMMAND %CPU TIME

56681 ruby 99.9 01:58.17

The most common approach to solve this problem is to use sleep statement:

queue = Queue.new loop do

puts "we need dequeue actions and do some job" unless queue.empty?

sleep 5

end

And it will help, but this is not perfect.

Imagine how the Ruby interpreter has to spend the time to switch between the main thread and worker’s threads every sleep interval to just realize that we have nothing to do because the worker queue is empty. This issue will be multiplied by a number of threads and get worse when the sleep interval has to become smaller.