From 26c490f404731d053a6205719b6246502c07b449 Mon Sep 17 00:00:00 2001 From: Patrick Simianer Date: Sat, 14 Jun 2014 16:46:27 +0200 Subject: init --- ruby/threads.rb | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100755 ruby/threads.rb (limited to 'ruby/threads.rb') diff --git a/ruby/threads.rb b/ruby/threads.rb new file mode 100755 index 0000000..ca2d0b2 --- /dev/null +++ b/ruby/threads.rb @@ -0,0 +1,37 @@ +#!/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) } + -- cgit v1.2.3