public
Created

Hamster.mutable_hash for fast, thread-safe R/W access to a Ruby Hash when more reads than writes. See: * http://stackoverflow.com/questions/1080993/pure-ruby-concurrent-hash * see: https://github.com/harukizaemon/hamster

  • Download Gist
ruby_mutable_hash_demo.rb
Ruby
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 38 39 40 41
require 'hamster'
require 'hamster/experimental/mutable_hash'
 
# a bunch of threads with a read/write ratio of 10:1
num_threads = 100
num_reads_per_write = 10
num_loops = 500
hsh = Hamster.mutable_hash
 
puts RUBY_DESCRIPTION
puts "#{num_threads} threads x #{num_loops} loops, #{num_reads_per_write}:1 R/W ratio"
 
t0 = Time.now
Thread.abort_on_exception = true
threads = (0...num_threads).map do |n|
Thread.new do
write_key = n % num_reads_per_write
read_keys = (0...num_reads_per_write).to_a.shuffle # random order
last_read = nil
num_loops.times do
read_keys.each do |k|
# Reads
last_read = hsh[k]
# keep things moving on MRI
Thread.pass
# Atomic increments in the correct ratio to reads
hsh.put(k) { |v| (v || 0) + 1 } if k == write_key
end
end
end
end
 
threads.map { |t| t.join }
t1 = Time.now
 
puts "Error in keys" unless (0...num_reads_per_write).to_a == hsh.keys.sort.to_a
puts "Error in values" unless hsh.values.all? { |v| v == (num_loops * num_threads) / num_reads_per_write }
puts "Time elapsed: #{t1 - t0} s"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.