Module: Psyllium::FiberClassMethods

Included in:
Fiber, Fiber
Defined in:
lib/psyllium/fiber.rb

Overview

Meant to be used with ‘extend` on Fiber class.

Instance Method Summary collapse

Instance Method Details

#start(*args, &block) ⇒ Object

A new method is used to create Psyllium Fibers for several reasons:

  1. This ensures that existing behavior for Fibers is not changed.

  2. Modifying the actual instances variables of Fibers does not work well

with certain schedulers like Async which expect to also wrap the given block in another block.

  1. The ‘start` method is also available on the `Thread` class, so this

makes it easy to change out one for the other.

Raises:

  • (ArgumentError)
[View source] [View on GitHub]

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/psyllium/fiber.rb', line 44

def start(*args, &block)
  raise ArgumentError.new('No block given') unless block

  Fiber.schedule do
    state = state_get(create_missing: true)
    state.mutex.synchronize do
      state.started = true
      state.value = block.call(*args)
    rescue StandardError => e
      state.exception = e
    ensure
      state.joined = true
    end
  end
end

#state_get(fiber: Fiber.current, create_missing: false) ⇒ Object

[View source] [View on GitHub]

60
61
62
63
64
65
66
67
68
69
70
# File 'lib/psyllium/fiber.rb', line 60

def state_get(fiber: Fiber.current, create_missing: false)
  # Psyllium state is a thread local variable because Fibers cannot (yet)
  # migrates across threads anyway.
  #
  # A `WeakKeyMap` is used so that when a Fiber is garbage collected, the
  # associated Psyllium::State will be garbage collected as well.
  state = Thread.current.thread_variable_get(:psyllium_state) || Thread.current.thread_variable_set(
    :psyllium_state, ObjectSpace::WeakKeyMap.new
  )
  create_missing ? (state[fiber] ||= State.new) : state[fiber]
end