Runs the given block synchronized with the argument given; i.e. for the same argument the block is never run in multiple threads simultaneously, while for different arguments the block can run in parallel in multiple threads.
This file contains 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
# synchronizes the given block, but only when called with the same argument | |
def synchronize_with_unique(arg, mutex, map, &block) | |
# get the lock for the supplied argument while increasing the refcount | |
lock_info = mutex.synchronize do | |
info = (map[arg] ||= { lock: Mutex.new, count: 0 }) | |
info[:count] += 1 | |
info | |
end | |
# do the actual locking | |
begin | |
lock_info[:lock].synchronize &block | |
ensure | |
# decrease the refcount and remove the lock from the hash if this was the last ref | |
mutex.synchronize do | |
map.delete(arg) if (lock_info[:count] -= 1) == 0 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment