Sha256: 0693b045a13c49f6b3e26dfd7ce9906c2fcfb8160da7edf1fe93780afd2d8779

Contents?: true

Size: 1.15 KB

Versions: 47

Compression:

Stored size: 1.15 KB

Contents

module Dynflow
  module Semaphores
    class Stateful < Abstract

      attr_reader :free, :tickets, :waiting, :meta

      def initialize(tickets, free = tickets, meta = {})
        @tickets = tickets
        @free = free
        @waiting = []
        @meta = meta
      end

      def wait(thing)
        if get > 0
          true
        else
          @waiting << thing
          false
        end
      end

      def get_waiting
        @waiting.shift
      end

      def has_waiting?
        !@waiting.empty?
      end

      def release(n = 1)
        @free += n
        @free = @tickets unless @tickets.nil? || @free <= @tickets
        save
      end

      def save
      end

      def get(n = 1)
        if n > @free
          drain
        else
          @free -= n
          save
          n
        end
      end

      def drain
        @free.tap do
          @free = 0
          save
        end
      end

      def to_hash
        {
          :tickets => @tickets,
          :free => @free,
          :meta => @meta
        }
      end

      def self.new_from_hash(hash)
        self.new(*hash.values_at(:tickets, :free, :meta))
      end
    end
  end
end

Version data entries

47 entries across 47 versions & 1 rubygems

Version Path
dynflow-1.3.0 lib/dynflow/semaphores/stateful.rb
dynflow-1.2.3 lib/dynflow/semaphores/stateful.rb
dynflow-1.2.2 lib/dynflow/semaphores/stateful.rb
dynflow-1.2.1 lib/dynflow/semaphores/stateful.rb
dynflow-1.2.0 lib/dynflow/semaphores/stateful.rb
dynflow-1.2.0.pre1 lib/dynflow/semaphores/stateful.rb
dynflow-1.1.6 lib/dynflow/semaphores/stateful.rb
dynflow-1.1.5 lib/dynflow/semaphores/stateful.rb
dynflow-1.1.4 lib/dynflow/semaphores/stateful.rb
dynflow-1.1.3 lib/dynflow/semaphores/stateful.rb
dynflow-1.1.2 lib/dynflow/semaphores/stateful.rb
dynflow-1.1.1 lib/dynflow/semaphores/stateful.rb
dynflow-1.1.0 lib/dynflow/semaphores/stateful.rb
dynflow-1.0.5 lib/dynflow/semaphores/stateful.rb
dynflow-1.0.4 lib/dynflow/semaphores/stateful.rb
dynflow-1.0.3 lib/dynflow/semaphores/stateful.rb
dynflow-1.0.2 lib/dynflow/semaphores/stateful.rb
dynflow-1.0.1 lib/dynflow/semaphores/stateful.rb
dynflow-1.0.0 lib/dynflow/semaphores/stateful.rb
dynflow-0.8.37 lib/dynflow/semaphores/stateful.rb