Class: Bunny::Concurrent::Condition

Inherits:
Object
  • Object
show all
Defined in:
lib/bunny/concurrent/condition.rb

Overview

Akin to java.util.concurrent.Condition and intrinsic object monitors (Object#wait, Object#notify, Object#notifyAll) in Java: threads can wait (block until notified) on a condition other threads notify them about. Unlike the j.u.c. version, this one has a single waiting set.

Conditions can optionally be annotated with a description string for ease of debugging.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(description = nil) ⇒ Condition

Returns a new instance of Condition.



17
18
19
20
21
# File 'lib/bunny/concurrent/condition.rb', line 17

def initialize(description = nil)
  @mutex           = Monitor.new
  @waiting_threads = []
  @description     = description
end

Instance Attribute Details

#descriptionObject (readonly)

Returns the value of attribute description.



14
15
16
# File 'lib/bunny/concurrent/condition.rb', line 14

def description
  @description
end

#waiting_threadsObject (readonly)

Returns the value of attribute waiting_threads.



14
15
16
# File 'lib/bunny/concurrent/condition.rb', line 14

def waiting_threads
  @waiting_threads
end

Instance Method Details

#any_threads_waiting?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/bunny/concurrent/condition.rb', line 57

def any_threads_waiting?
  @mutex.synchronize { !@waiting_threads.empty? }
end

#none_threads_waiting?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/bunny/concurrent/condition.rb', line 61

def none_threads_waiting?
  @mutex.synchronize { @waiting_threads.empty? }
end

#notifyObject



32
33
34
35
36
37
38
39
40
41
# File 'lib/bunny/concurrent/condition.rb', line 32

def notify
  @mutex.synchronize do
    t = @waiting_threads.shift
    begin
      t.run if t
    rescue ThreadError
      retry
    end
  end
end

#notify_allObject



43
44
45
46
47
48
49
50
51
# File 'lib/bunny/concurrent/condition.rb', line 43

def notify_all
  @mutex.synchronize do
    @waiting_threads.each do |t|
      t.run
    end

    @waiting_threads.clear
  end
end

#waitObject



23
24
25
26
27
28
29
30
# File 'lib/bunny/concurrent/condition.rb', line 23

def wait
  @mutex.synchronize do
    t = Thread.current
    @waiting_threads.push(t)
  end

  Thread.stop
end

#waiting_set_sizeObject



53
54
55
# File 'lib/bunny/concurrent/condition.rb', line 53

def waiting_set_size
  @mutex.synchronize { @waiting_threads.size }
end