-
-
Save practicingruby/5187839 to your computer and use it in GitHub Desktop.
| require "thread" | |
| class TransactionalMap | |
| TransactionAborted = Class.new(StandardError) | |
| def initialize | |
| @data = [{}] | |
| @version = 0 | |
| @write_lock = Mutex.new | |
| @update_lock = Mutex.new | |
| end | |
| def [](key) | |
| @data[@version][key] | |
| end | |
| def []=(key, value) | |
| @write_lock.synchronize do | |
| @data[@version + 1] = @data[@version].merge(key => value) | |
| @version += 1 | |
| end | |
| end | |
| def update(&block) | |
| @update_lock.synchronize do | |
| begin | |
| starting_version = @version | |
| block.call | |
| rescue StandardError => e | |
| undo until @version == starting_version | |
| raise e unless TransactionAborted === e | |
| end | |
| end | |
| end | |
| def abort | |
| raise TransactionAborted | |
| end | |
| def inspect | |
| "#{@data[@version].inspect} -- v#{@version}" | |
| end | |
| def undo | |
| @write_lock.synchronize do | |
| raise "Can't undo!" if @version == 0 | |
| @version -= 1 | |
| end | |
| end | |
| def redo | |
| @write_lock.synchronize do | |
| raise "Can't redo!" unless @version < @data.size - 1 | |
| @version += 1 | |
| end | |
| end | |
| end | |
| map = TransactionalMap.new | |
| map[:a] = 0 | |
| N = 100 | |
| M = 1000 | |
| N.times.map do | |
| Thread.new do | |
| M.times do | |
| map.update do | |
| map[:a] += 1 | |
| end | |
| end | |
| end | |
| end.map(&:join) | |
| p map[:a] |
@judofyr: Good catch. This was just an experiment and I was relying entirely on the inspect output. Fixed!
What's the concurrency guarantees of #update?
The following code returns "10" although the incrementing happens 100 times (10 threads * 10 iterations). I'm not sure if this is expected behavior or not:
require_relative 'x'
map = TransactionalMap.new
map[:a] = 0
N = 10
M = 10
N.times.map do
Thread.new do
M.times do
map.update do
val = map[:a]
# Do work
sleep(rand * 0.01)
map[:a] = val + 1
end
end
end
end.map(&:join)
p map[:a]Right now it seems that the transactions are not thread-safe (e.g. it's neither STM nor a mutex around #update), so the only "transactional" thing about is being able to rollback/undo. You'd still have to use a mutex yourself if you want atomic transactions.
This snippet here never returns the correct answer (100000) in JRuby:
require_relative 'x'
map = TransactionalMap.new
map[:a] = 0
N = 100
M = 1000
N.times.map do
Thread.new do
M.times do
map.update do
map[:a] += 1
end
end
end
end.map(&:join)
p map[:a]@judofyr: I had suspected something was buggy in my locking mechanism, but I'm terrible at concurrency. How about the updated code?
TransactionalMap#[] seems broken:
undefined method #version