Created
January 9, 2013 20:23
-
-
Save anonymous/4496537 to your computer and use it in GitHub Desktop.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment