Sha256: 8c73e449ba78ca661f83cdcb2e8832b4133601ce26351fd52ec3f37fc14a0104

Contents?: true

Size: 1.22 KB

Versions: 3

Compression:

Stored size: 1.22 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
      @holding_fiber = Fiber.current
      yield
    ensure
      @holding_fiber = nil
      @store << @token if @token
    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
      Thread.current.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

3 entries across 3 versions & 1 rubygems

Version Path
polyphony-0.45.4 lib/polyphony/core/sync.rb
polyphony-0.45.2 lib/polyphony/core/sync.rb
polyphony-0.45.1 lib/polyphony/core/sync.rb