Sha256: 7d8e0013e1d0772d0b534e8919605772e410f5f88264eebff34d5342ee4ddce3

Contents?: true

Size: 1.48 KB

Versions: 13

Compression:

Stored size: 1.48 KB

Contents

require "thread"

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


      def initialize(description = nil)
        @mutex           = Mutex.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

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
bunny-0.9.0.pre13 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre12 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre11 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre10 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre9 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre8 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre7 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre6 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre5 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre4 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre3 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre2 lib/bunny/concurrent/condition.rb
bunny-0.9.0.pre1 lib/bunny/concurrent/condition.rb