#!/usr/bin/env ruby require 'thread' prev = 'z' ('a'..'r').each { |i| Marshal.dump({i=>1,prev=>1,'x'=>1}, File.new("test.#{i}", 'wb')) prev = i } a = [] threads = [] mutex = Mutex.new ('a'..'r').each { |i| threads << Thread.new(i) { |c| mutex.synchronize { puts c } h = Marshal.load(File.new('test.'+c, 'rb')) puts "#{c} x" mutex.synchronize { a << h } } } threads.each { |t| t.join } puts '--' threads = [] while a.size > 1 threads << Thread.new { i = j = nil mutex.synchronize { i = a.pop; j = a.pop } i.merge!(j) { |k,v,w| v+w } mutex.synchronize { a << i } } threads.each { |t| t.join } end File.open('counts.merged', 'wb') { |f| Marshal.dump(a[0], f) }