Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Hamster.mutable_hash for fast, thread-safe R/W access to a Ruby Hash when more reads than writes. See: * * see:
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 "#{num_threads} threads x #{num_loops} loops, #{num_reads_per_write}:1 R/W ratio"
t0 =
Thread.abort_on_exception = true
threads = (0...num_threads).map do |n| 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
# Atomic increments in the correct ratio to reads
hsh.put(k) { |v| (v || 0) + 1 } if k == write_key
end { |t| t.join }
t1 =
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
You can’t perform that action at this time.