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.



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

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

Instance Attribute Details

#descriptionObject (readonly)

Returns the value of attribute description.



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

def description
  @description
end

#waiting_threadsObject (readonly)

Returns the value of attribute waiting_threads.



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

def waiting_threads
  @waiting_threads
end

Instance Method Details

#any_threads_waiting?Boolean

Returns:

  • (Boolean)


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

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

#none_threads_waiting?Boolean

Returns:

  • (Boolean)


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

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

#notifyObject



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

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

#notify_allObject



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

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

    @waiting_threads.clear
  end
end

#waitObject



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

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

  Thread.stop
end

#waiting_set_sizeObject



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

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