Class: Green::Semaphore

Inherits:
Object
  • Object
show all
Defined in:
lib/green/semaphore.rb

Direct Known Subclasses

Mutex

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = 1) ⇒ Semaphore

Returns a new instance of Semaphore.



4
5
6
7
8
# File 'lib/green/semaphore.rb', line 4

def initialize(value = 1)
  @value = value
  @counter = value
  @links = []
end

Instance Attribute Details

#counterObject

Returns the value of attribute counter.



3
4
5
# File 'lib/green/semaphore.rb', line 3

def counter
  @counter
end

#valueObject

Returns the value of attribute value.



3
4
5
# File 'lib/green/semaphore.rb', line 3

def value
  @value
end

Instance Method Details

#acquireObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/green/semaphore.rb', line 14

def acquire
  if counter > 0
    self.counter -= 1
    true
  else
    g = Green.current
    clb = rawlink { g.switch }
    Green.hub.wait { unlink clb }
    self.counter -= 1
    true
  end
end


36
37
38
39
# File 'lib/green/semaphore.rb', line 36

def rawlink(&clb)
  @links << clb
  clb
end

#releaseObject



27
28
29
30
31
32
33
34
# File 'lib/green/semaphore.rb', line 27

def release
  self.counter += 1
  wait_links.dup.each(&:call)
  if @links.size > 0
    l = @links.pop
    Green.hub.callback { l.call }
  end      
end


41
42
43
# File 'lib/green/semaphore.rb', line 41

def unlink(clb)
  @links.delete clb
end

#wait(v = value) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/green/semaphore.rb', line 45

def wait(v = value)
  if counter >= v
    return counter
  else
    g = Green.current
    clb = proc do          
      if counter >= v && @links.size == 0
        wait_links.delete clb
        Green.hub.callback { g.switch }            
      end
    end
    wait_links << clb
    Green.hub.wait { wait_links.delete clb }
  end
end

#wait_avaliableObject



61
62
63
# File 'lib/green/semaphore.rb', line 61

def wait_avaliable
  wait value - 1
end


10
11
12
# File 'lib/green/semaphore.rb', line 10

def wait_links
  @wait_links ||= []
end