Class: Knj::Mutexcl
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(args = {}) ⇒ Mutexcl
constructor
A new instance of Mutexcl.
- #sync(mode) ⇒ Object
Constructor Details
#initialize(args = {}) ⇒ Mutexcl
Returns a new instance of Mutexcl.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/knj/mutexcl.rb', line 2 def initialize(args = {}) @args = args raise "No ':modes' given in arguments." if !@args.key?(:modes) @mutex = Mutex.new @blocked = {} @args[:modes].each do |mode, data| data[:blocks].each do |block| @blocked[block] = { :mutex => Mutex.new, :count => 0 } end end end |
Class Method Details
Instance Method Details
#sync(mode) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/knj/mutexcl.rb', line 26 def sync(mode) raise "No such mode: '#{mode}'." if !@args[:modes].key?(mode) while @blocked[mode][:count].to_i > 0 STDOUT.print "Sleeping because blocked '#{mode}' (#{@blocked[mode][:count]}).\n" sleep 0.1 end @mutex.synchronize do @args[:modes][mode][:blocks].each do |block| @blocked[block][:count] += 1 end end begin yield ensure @args[:modes][mode][:blocks].each do |block| @blocked[block][:count] -= 1 end end end |