Sha256: 72c20755bf50d10f19c297c0f7c488c336edb1a75f2fdb2bd3dc3f1abf1ce6fb

Contents?: true

Size: 1.24 KB

Versions: 4

Compression:

Stored size: 1.24 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
  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

4 entries across 4 versions & 1 rubygems

Version Path
polyphony-0.53.2 lib/polyphony/core/sync.rb
polyphony-0.53.1 lib/polyphony/core/sync.rb
polyphony-0.53.0 lib/polyphony/core/sync.rb
polyphony-0.52.0 lib/polyphony/core/sync.rb