Class: LightIO::Core::Beam

Inherits:
LightFiber show all
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

#ioloop

Class Method Summary collapse

Instance Method Summary collapse

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 }

Parameters:

  • args (Array)

    pass arguments to Beam block

  • blk (Proc)

    block to execute

Raises:



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

.passnil

Schedule beams

normally beam should be auto scheduled, use this method to manually trigger a schedule

Returns:

  • (nil)


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

Returns:

  • (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

Parameters:

  • limit (Numeric) (defaults to: 0)

    wait limit seconds if limit > 0, return nil if beam still alive, else return beam self

Returns:



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

#killBeam

Kill beam

Returns:



91
92
93
94
95
# File 'lib/lightio/core/beam.rb', line 91

def kill
  dead
  parent.transfer if self == Beam.current
  self
end

#valueObject

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