Using JRuby native Queue to manage work across threads

In this code snippet, I’ll show an example of how to use a native Ruby Queue to manage work across threads. I used JRuby to not be bound by a global interpreter lock, which allows use of all CPU cores at once. The code uses “java.lang.Runtime.getRuntime.available_processors” to get a count of the number of CPU cores and “tput cols” to get the column width of your terminal (although it did not work perfect in my environment, sometimes defaulting to 80). When executed you should see the activity of all your CPU cores max out, and clusters of “*” (based on the number of CPU cores) should print across your terminal.

#!/usr/bin/env jruby

# to generate random hex strings
require 'securerandom'

# get number of cpu cores
worker_count = java.lang.Runtime.getRuntime.available_processors

# get number of terminal columns
terminal_cols = `tput cols`.strip.to_i

# create new queue, and add each column number
q = Queue.new
(1..terminal_cols).each {|t| q.push t }

# create a worker for number of cpu cores
workers = (1..worker_count).map do
  Thread.new do
    # interate while q is not empty
    while (x = q.empty? ? false : q.pop(true))

      # do some work
      1_000_000.times { SecureRandom.hex.reverse }

      # output character to show work is done
      print '*'
    end
  end
end
# wait for threads
workers.map(&:join)
puts

Updated: