File: condition.rb

package info (click to toggle)
ruby-bunny 2.23.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,644 kB
  • sloc: ruby: 10,256; sh: 70; makefile: 8
file content (66 lines) | stat: -rw-r--r-- 1,563 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require "thread"
require "monitor"

module Bunny
  # @private
  module Concurrent
    # 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.
    # @private
    class Condition
      attr_reader :waiting_threads, :description


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

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

        Thread.stop
      end

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

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

          @waiting_threads.clear
        end
      end

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

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

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