Class: Julewire::Core::Scheduling::DeadlineScheduler

Inherits:
Object
  • Object
show all
Defined in:
lib/julewire/core/scheduling/deadline_scheduler.rb

Defined Under Namespace

Classes: Entry

Constant Summary collapse

CLOCK =
Process::CLOCK_MONOTONIC

Instance Method Summary collapse

Constructor Details

#initialize(thread_name:, idle: :keep_alive) ⇒ DeadlineScheduler

Returns a new instance of DeadlineScheduler.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/julewire/core/scheduling/deadline_scheduler.rb', line 11

def initialize(thread_name:, idle: :keep_alive)
  @thread_name = thread_name
  @idle = idle
  @mutex = Mutex.new
  @condition = ConditionVariable.new
  @entries = {}
  # A heap keeps timeout scheduling cheap without non-shareable scheduler dependencies.
  @heap = []
  @next_token = 0
  @generation = 0
  @pid = Process.pid
  @thread = nil
end

Instance Method Details

#after_fork!Object



54
55
56
57
58
59
60
61
62
# File 'lib/julewire/core/scheduling/deadline_scheduler.rb', line 54

def after_fork!
  if @pid == Process.pid
    reset_same_process
  else
    reset_after_fork
  end

  self
end

#cancel(token) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/julewire/core/scheduling/deadline_scheduler.rb', line 45

def cancel(token)
  return unless token

  @mutex.synchronize do
    @entries.delete(token)
    @condition.signal
  end
end

#schedule(timeout, &block) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/julewire/core/scheduling/deadline_scheduler.rb', line 25

def schedule(timeout, &block)
  raise ArgumentError, "block required" unless block

  timeout = Float(timeout)
  if timeout <= 0
    yield
    return
  end

  @mutex.synchronize do
    token = next_token
    entry = Entry.new(monotonic_time + timeout, token, block)
    @entries[token] = entry
    heap_push(entry)
    ensure_thread
    @condition.signal
    token
  end
end