Module: ExcADG::RTimeout

Included in:
Vertex
Defined in:
lib/excadg/rtimeout.rb

Overview

simple ractor-safe timeout implementation

Defined Under Namespace

Classes: TimedOutError

Class Method Summary collapse

Class Method Details

.await(timeout: nil, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/excadg/rtimeout.rb', line 8

def await timeout: nil, &block
  return block.call if timeout.nil? || timeout.zero?

  timed_out = false
  Thread.report_on_exception = false
  payload = Thread.new { Thread.current[:result] = block.call }
  countdown_t = Thread.new {
    sleep timeout
    payload.kill
    timed_out = true
  }

  payload.join
  countdown_t.kill
  timed_out ? raise(TimedOutError) : payload[:result]
end