Class: LightIO::Core::Beam
- Inherits:
-
LightFiber
- Object
- Fiber
- LightFiber
- LightIO::Core::Beam
- Defined in:
- lib/lightio/core/beam.rb
Overview
Beam is light-weight executor, provide thread-like interface
@Example:
#- initialize with block
b = Beam.new{puts "hello"}
b.join
#output: hello
b = Beam.new(1,2,3){|one, two, three| puts [one, two, three].join(",") }
b.join
#output: 1,2,3
#- use join wait beam done
b = Beam.new(){LightIO.sleep 3}
b.join
b.alive? # false
Instance Attribute Summary
Attributes inherited from LightFiber
Class Method Summary collapse
-
.pass ⇒ nil
Schedule beams.
Instance Method Summary collapse
- #alive? ⇒ Boolean
-
#initialize(*args, &blk) ⇒ Beam
constructor
Create a new beam.
-
#join(limit = 0) ⇒ Beam?
Block and wait beam dead.
-
#kill ⇒ Beam
Kill beam.
-
#value ⇒ Object
block and wait beam return a value.
Constructor Details
#initialize(*args, &blk) ⇒ Beam
Create a new beam
Beam is light-weight executor, provide thread-like interface
Beam.new(“hello”){|hello| puts hello }
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/lightio/core/beam.rb', line 29 def initialize(*args, &blk) raise Error, "must be called with a block" unless blk super() { begin @value = yield(*args) rescue StandardError => e @error = e end # mark as dead dead # transfer back to parent(caller fiber) after schedule parent.transfer } # schedule beam in ioloop ioloop.add_callback {transfer} @alive = true end |
Class Method Details
.pass ⇒ nil
Schedule beams
normally beam should be auto scheduled, use this method to manually trigger a schedule
104 105 106 107 |
# File 'lib/lightio/core/beam.rb', line 104 def pass schedule = LightIO::Watchers::Schedule.new IOloop.current.wait(schedule) end |
Instance Method Details
#alive? ⇒ Boolean
47 48 49 |
# File 'lib/lightio/core/beam.rb', line 47 def alive? super && @alive end |
#join(limit = 0) ⇒ Beam?
Block and wait beam dead
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/lightio/core/beam.rb', line 65 def join(limit=0) # try directly get result if !alive? || limit <= 0 # call value to raise error value return self end # set a transfer back timer parent = Beam.current timer = LightIO::Watchers::Timer.new(limit) timer.set_callback {parent.transfer} ioloop.add_timer(timer) ioloop.transfer if alive? nil else check_and_raise_error self end end |
#kill ⇒ Beam
Kill beam
91 92 93 94 95 |
# File 'lib/lightio/core/beam.rb', line 91 def kill dead parent.transfer if self == Beam.current self end |
#value ⇒ Object
block and wait beam return a value
52 53 54 55 56 57 58 59 |
# File 'lib/lightio/core/beam.rb', line 52 def value if alive? self.parent = Beam.current ioloop.transfer end check_and_raise_error @value end |