Class: Concurrent::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent/atomic/event.rb

Overview

Old school kernel-style event reminiscent of Win32 programming in C++.

When an Event is created it is in the unset state. Threads can choose to #wait on the event, blocking until released by another thread. When one thread wants to alert all blocking threads it calls the #set method which will then wake up all listeners. Once an Event has been set it remains set. New threads calling #wait will return immediately. An Event may be #reset at any time once it has been set.

Instance Method Summary collapse

Constructor Details

#initializeEvent

Creates a new Event in the unset state. Threads calling #wait on the Event will block.



20
21
22
23
24
# File 'lib/concurrent/atomic/event.rb', line 20

def initialize
  @set = false
  @mutex = Mutex.new
  @condition = Condition.new
end

Instance Method Details

#resetBoolean

Reset a previously set event back to the unset state. Has no effect if the Event has not yet been set.

Returns:

  • should always return true



70
71
72
73
74
75
76
# File 'lib/concurrent/atomic/event.rb', line 70

def reset
  @mutex.lock
  @set = false
  true
ensure
  @mutex.unlock
end

#setBoolean

Trigger the event, setting the state to set and releasing all threads waiting on the event. Has no effect if the Event has already been set.

Returns:

  • should always return true



40
41
42
43
44
45
46
47
48
49
# File 'lib/concurrent/atomic/event.rb', line 40

def set
  @mutex.lock
  unless @set
    @set = true
    @condition.broadcast
  end
  true
ensure
  @mutex.unlock
end

#set?Boolean

Is the object in the set state?

Returns:

  • indicating whether or not the Event has been set



29
30
31
32
33
34
# File 'lib/concurrent/atomic/event.rb', line 29

def set?
  @mutex.lock
  @set
ensure
  @mutex.unlock
end

#try?Boolean

Returns:



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/concurrent/atomic/event.rb', line 51

def try?
  @mutex.lock

  if @set
    false
  else
    @set = true
    @condition.broadcast
    true
  end

ensure
  @mutex.unlock
end

#wait(timeout = nil) ⇒ Boolean

Wait a given number of seconds for the Event to be set by another thread. Will wait forever when no timeout value is given. Returns immediately if the Event has already been set.

Returns:

  • true if the Event was set before timeout else false



83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/concurrent/atomic/event.rb', line 83

def wait(timeout = nil)
  @mutex.lock

  unless @set
    remaining = Condition::Result.new(timeout)
    while !@set && remaining.can_wait?
      remaining = @condition.wait(@mutex, remaining.remaining_time)
    end
  end

  @set
ensure
  @mutex.unlock
end