Sha256: 26c363215b8218b81b471a58bb1a07f94608de0c279a7fb30e758a272e5fab8d

Contents?: true

Size: 1.35 KB

Versions: 28

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

module Polyphony
  # Implements mutex lock for synchronizing access to a shared resource
  class Mutex
    def initialize
      @store = Queue.new
      @store << :token
    end

    def synchronize(&block)
      return yield if @holding_fiber == Fiber.current

      synchronize_not_holding(&block)
    end

    def synchronize_not_holding
      @token = @store.shift
      begin
        @holding_fiber = Fiber.current
        yield
      ensure
        @holding_fiber = nil
        @store << @token if @token
      end
    end

    def conditional_release
      @store << @token
      @token = nil
      @holding_fiber = nil
    end

    def conditional_reacquire
      @token = @store.shift
      @holding_fiber = Fiber.current
    end

    def owned?
      @holding_fiber == Fiber.current
    end

    def locked?
      @holding_fiber
    end
  end

  # Implements a fiber-aware ConditionVariable
  class ConditionVariable
    def initialize
      @queue = Polyphony::Queue.new
    end

    def wait(mutex, _timeout = nil)
      mutex.conditional_release
      @queue << Fiber.current
      Polyphony.backend_wait_event(true)
      mutex.conditional_reacquire
    end

    def signal
      fiber = @queue.shift
      fiber.schedule
    end

    def broadcast
      while (fiber = @queue.shift)
        fiber.schedule
      end
    end
  end
end

Version data entries

28 entries across 28 versions & 1 rubygems

Version Path
polyphony-0.79 lib/polyphony/core/sync.rb
polyphony-0.78 lib/polyphony/core/sync.rb
polyphony-0.77 lib/polyphony/core/sync.rb
polyphony-0.76 lib/polyphony/core/sync.rb
polyphony-0.75 lib/polyphony/core/sync.rb
polyphony-0.74 lib/polyphony/core/sync.rb
polyphony-0.73.1 lib/polyphony/core/sync.rb
polyphony-0.73 lib/polyphony/core/sync.rb
polyphony-0.72 lib/polyphony/core/sync.rb
polyphony-0.71 lib/polyphony/core/sync.rb
polyphony-0.70 lib/polyphony/core/sync.rb
polyphony-0.69 lib/polyphony/core/sync.rb
polyphony-0.68 lib/polyphony/core/sync.rb
polyphony-0.67 lib/polyphony/core/sync.rb
polyphony-0.66 lib/polyphony/core/sync.rb
polyphony-0.65 lib/polyphony/core/sync.rb
polyphony-0.64 lib/polyphony/core/sync.rb
polyphony-0.63 lib/polyphony/core/sync.rb
polyphony-0.62 lib/polyphony/core/sync.rb
polyphony-0.61 lib/polyphony/core/sync.rb