summaryrefslogtreecommitdiff
path: root/ruby/threads.rb
blob: ca2d0b21d1fb6d7d43b5609b49591f4d0821ccfb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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) }