Skip to content

Instantly share code, notes, and snippets.

@bmarini
Created May 4, 2013 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmarini/5518239 to your computer and use it in GitHub Desktop.
Save bmarini/5518239 to your computer and use it in GitHub Desktop.
Playing with threads and queues.
#!/usr/bin/env ruby
require 'thread'
# Usage ./list-files [DIRECTORY]
WORKERS = 5
queue = Queue.new
@results = Queue.new
threads = []
dir = ARGV[0]
def process_file(filename)
@results.push [ File.size(filename), filename ]
end
puts "Listing files in #{dir}"
Dir["#{dir}/*"].each { |filename| queue.push filename }
WORKERS.times do
threads << Thread.new do
process_file queue.pop until queue.empty?
end
end
threads.each(&:join)
p @results.pop until @results.empty?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment