Class: Fiber

Inherits:
Object show all
Defined in:
lib/ramaze/snippets/fiber.rb

Direct Known Subclasses

Ramaze::Fiber

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Fiber) initialize

A new instance of Fiber

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
# File 'lib/ramaze/snippets/fiber.rb', line 7

def initialize
  raise ArgumentError, 'new Fiber requires a block' unless block_given?

  @yield = Queue.new
  @resume = Queue.new

  @thread = Thread.new{ @yield.push [*yield(*wait)] }
  @thread.abort_on_exception = true
  @thread[:fiber] = self
end

Instance Attribute Details

- (Object) thread (readonly)

Returns the value of attribute thread



17
18
19
# File 'lib/ramaze/snippets/fiber.rb', line 17

def thread
  @thread
end

- (Object) yield (readonly)

Returns the value of attribute yield



17
18
19
# File 'lib/ramaze/snippets/fiber.rb', line 17

def yield
  @yield
end

Class Method Details

+ (Object) yield(*args)

Raises:



30
31
32
33
34
35
# File 'lib/ramaze/snippets/fiber.rb', line 30

def self.yield *args
  raise FiberError, "can't yield from root fiber" unless fiber = Thread.current[:fiber]
  fiber.yield.push(args)
  result = fiber.wait
  result.size > 1 ? result : result.first
end

Instance Method Details

- (Object) inspect



37
38
39
# File 'lib/ramaze/snippets/fiber.rb', line 37

def inspect
  "#<#{self.class}:0x#{self.object_id.to_s(16)}>"
end

- (Object) resume(*args)

Raises:



19
20
21
22
23
24
# File 'lib/ramaze/snippets/fiber.rb', line 19

def resume *args
  raise FiberError, 'dead fiber called' unless @thread.alive?
  @resume.push(args)
  result = @yield.pop
  result.size > 1 ? result : result.first
end

- (Object) wait



26
27
28
# File 'lib/ramaze/snippets/fiber.rb', line 26

def wait
  @resume.pop
end