The library concurrent-ruby has a lot of primitives for concurrency.
For example, it has a thread-safe implementation Hash
.
There are also classes for doing immutable values and thread-safe variables.
For example:
require 'concurrent'
variable = { n: 0 }
lock = Concurrent::ReadWriteLock.new
t1 = Thread.new do
30.times {
lock.with_write_lock {
variable[:n] = variable[:n] + 1
puts 'Writer 1 wrote'
}
sleep 0.5
}
end
t2 = Thread.new do
30.times {
lock.with_write_lock {
variable[:n] = variable[:n] + 1
puts 'Writer 2 wrote'
}
sleep 0.5
}
end
t3 = Thread.new do
20.times {
lock.with_read_lock { puts 'Reading', variable[:n] }
sleep 1
}
end
t1.join
t2.join
t3.join