Class: Green::Semaphore
- Inherits:
-
Object
- Object
- Green::Semaphore
- Defined in:
- lib/green/semaphore.rb
Direct Known Subclasses
Instance Attribute Summary collapse
-
#counter ⇒ Object
Returns the value of attribute counter.
-
#value ⇒ Object
Returns the value of attribute value.
Instance Method Summary collapse
- #acquire ⇒ Object
-
#initialize(value = 1) ⇒ Semaphore
constructor
A new instance of Semaphore.
- #rawlink(&clb) ⇒ Object
- #release ⇒ Object
- #unlink(clb) ⇒ Object
- #wait(v = value) ⇒ Object
- #wait_avaliable ⇒ Object
- #wait_links ⇒ Object
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
#counter ⇒ Object
Returns the value of attribute counter.
3 4 5 |
# File 'lib/green/semaphore.rb', line 3 def counter @counter end |
#value ⇒ Object
Returns the value of attribute value.
3 4 5 |
# File 'lib/green/semaphore.rb', line 3 def value @value end |
Instance Method Details
#acquire ⇒ Object
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 |
#rawlink(&clb) ⇒ Object
36 37 38 39 |
# File 'lib/green/semaphore.rb', line 36 def rawlink(&clb) @links << clb clb end |
#release ⇒ Object
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 |
#unlink(clb) ⇒ Object
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_avaliable ⇒ Object
61 62 63 |
# File 'lib/green/semaphore.rb', line 61 def wait_avaliable wait value - 1 end |
#wait_links ⇒ Object
10 11 12 |
# File 'lib/green/semaphore.rb', line 10 def wait_links @wait_links ||= [] end |