Module: Litescheduler

Defined in:
lib/litestack/litescheduler.rb

Overview

frozen_stringe_literal: true

Class Method Summary collapse

Class Method Details

.backendObject

cache the scheduler we are running in it is an error to change the scheduler for a process or for a child forked from that process



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/litestack/litescheduler.rb', line 7

def self.backend
  @backend ||= if Fiber.scheduler
    :fiber
  elsif defined? Polyphony
    :polyphony
  elsif defined? Iodine
    :iodine
  else
    :threaded
  end
end

.currentObject



39
40
41
42
43
44
45
# File 'lib/litestack/litescheduler.rb', line 39

def self.current
  if fiber_backed?
    Fiber.current
  else
    Thread.current
  end
end

.max_contextsObject



74
75
76
77
# File 'lib/litestack/litescheduler.rb', line 74

def self.max_contexts
  return 50 if fiber_backed?
  5
end

.mutexObject

mutex initialization



80
81
82
83
# File 'lib/litestack/litescheduler.rb', line 80

def self.mutex
  # a single mutex per process (is that ok?)
  @@mutex ||= Mutex.new
end

.spawn(&block) ⇒ Object

spawn a new execution context



20
21
22
23
24
25
26
27
28
29
# File 'lib/litestack/litescheduler.rb', line 20

def self.spawn(&block)
  if backend == :fiber
    Fiber.schedule(&block)
  elsif backend == :polyphony
    spin(&block)
  elsif (backend == :threaded) || (backend == :iodine)
    Thread.new(&block)
  end
  # we should never reach here
end

.storageObject



31
32
33
34
35
36
37
# File 'lib/litestack/litescheduler.rb', line 31

def self.storage
  if fiber_backed?
    Fiber.current.storage
  else
    Thread.current
  end
end

.switchObject

switch the execution context to allow others to run



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/litestack/litescheduler.rb', line 48

def self.switch
  if backend == :fiber
    Fiber.scheduler.yield
    true
  elsif backend == :polyphony
    Fiber.current.schedule
    Thread.current.switch_fiber
    true
  else
    # Thread.pass
    false
  end
end

.synchronize(fiber_sync = false, &block) ⇒ Object

bold assumption, we will only synchronize threaded code! If some code explicitly wants to synchronize a fiber they must send (true) as a parameter to this method else it is a no-op for fibers



66
67
68
69
70
71
72
# File 'lib/litestack/litescheduler.rb', line 66

def self.synchronize(fiber_sync = false, &block)
  if fiber_backed?
    yield # do nothing, just run the block as is
  else
    mutex.synchronize(&block)
  end
end