summaryrefslogtreecommitdiff
path: root/ruby/threads.rb
diff options
context:
space:
mode:
Diffstat (limited to 'ruby/threads.rb')
-rwxr-xr-xruby/threads.rb37
1 files changed, 37 insertions, 0 deletions
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) }
+