Class: QuackConcurrency::Sleeper

Inherits:
Object
  • Object
show all
Defined in:
lib/quack_concurrency/sleeper.rb

Overview

A Sleeper can be used to preemptively wake a thread that will be put to sleep in the future.

A thread can only be put to sleep and woken once for each Sleeper.

Direct Known Subclasses

SafeSleeper

Instance Method Summary collapse

Constructor Details

#initializeSleeper

Creates a new QuackConcurrency::Sleeper concurrency tool.



10
11
12
13
14
15
16
# File 'lib/quack_concurrency/sleeper.rb', line 10

def initialize
  @state = :initial
  @mutex = ::Mutex.new
  @condition_variable = ::ConditionVariable.new
  @sleep_called = false
  @wake_called = false
end

Instance Method Details

#sleep(timeout = nil) ⇒ Float

Puts this thread to sleep. Will be skipped if #wake has already been called. If called without a timeout it will sleep forever. It can only be called once.

Parameters:

  • timeout (nil, Numeric) (defaults to: nil)

    maximum time to sleep in seconds, nil for forever

Returns:

  • (Float)

    duration of time the thread was asleep in seconds

Raises:

  • (TypeError)

    if timeout is not nil or Numeric

  • (ArgumentError)

    if timeout is negative

  • (RuntimeError)

    if already called once

  • (Exception)

    any exception raised by ConditionVariable#wait (eg. interrupts, ThreadError)



28
29
30
31
32
33
34
35
36
# File 'lib/quack_concurrency/sleeper.rb', line 28

def sleep(timeout = nil)
  timeout = process_timeout(timeout)
  enforce_sleep_call_limit
  @mutex.synchronize do
    timer do
      @condition_variable.wait(@mutex, timeout) unless @wake_called
    end
  end
end

#wakevoid

This method returns an undefined value.

Wake it’s sleeping thread, if one exists. It can only be called once.

Raises:

  • (RuntimeError)

    if already called once



42
43
44
45
46
47
48
# File 'lib/quack_concurrency/sleeper.rb', line 42

def wake
  @mutex.synchronize do
    enforce_wake_call_limit
    @condition_variable.signal
  end
  nil
end