Created
July 13, 2011 02:59
-
-
Save tomotaka/1079629 to your computer and use it in GitHub Desktop.
offering exclusive locking resources for multithread
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
class ExResourceLock | |
def initialize(map) | |
@rmap = map | |
@mtx = Mutex.new | |
@cv = ConditionVariable.new | |
@mtx.synchronize do | |
@free_resources = @rmap.keys | |
@locked_resources = [] | |
end | |
end | |
def assign_and_lock | |
resource_name = nil | |
resource = nil | |
@mtx.synchronize do | |
while @free_resources.empty? do | |
@cv.wait(@mtx) | |
end | |
resource_name = @free_resources.pop | |
resource = @rmap[resource_name] | |
end | |
return [resource_name, resource] | |
end | |
def unlock(resource_name) | |
@mtx.synchronize do | |
@free_resources << resource_name | |
@locked_resources.delete(resource_name) | |
@cv.signal | |
end | |
self | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment