Class: Knj::Mutexcl

Inherits:
Object show all
Defined in:
lib/knj/mutexcl.rb

Class Method Summary collapse

Instance Method Summary collapse

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

.rwObject



17
18
19
20
21
22
23
24
# File 'lib/knj/mutexcl.rb', line 17

def self.rw
  return Knj::Mutexcl.new(
    :modes => {
      :reader => {:blocks => [:writer]},
      :writer => {:blocks => [:writer, :reader]}
    }
  )
end

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