Created
May 4, 2013 18:00
-
-
Save bmarini/5518239 to your computer and use it in GitHub Desktop.
Playing with threads and queues.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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