Sha256: 9c0db1f5cbc977d68ac8fb17a351631f32d3af8634c5430b6bdcbb7ef0dc1788

Contents?: true

Size: 1.25 KB

Versions: 17

Compression:

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

17 entries across 17 versions & 1 rubygems

Version Path
polyphony-0.51.0 lib/polyphony/core/sync.rb
polyphony-0.50.1 lib/polyphony/core/sync.rb
polyphony-0.50.0 lib/polyphony/core/sync.rb
polyphony-0.49.2 lib/polyphony/core/sync.rb
polyphony-0.49.1 lib/polyphony/core/sync.rb
polyphony-0.49.0 lib/polyphony/core/sync.rb
polyphony-0.48.0 lib/polyphony/core/sync.rb
polyphony-0.47.5.1 lib/polyphony/core/sync.rb
polyphony-0.47.5 lib/polyphony/core/sync.rb
polyphony-0.47.4 lib/polyphony/core/sync.rb
polyphony-0.47.3 lib/polyphony/core/sync.rb
polyphony-0.47.2 lib/polyphony/core/sync.rb
polyphony-0.47.1 lib/polyphony/core/sync.rb
polyphony-0.47.0 lib/polyphony/core/sync.rb
polyphony-0.46.1 lib/polyphony/core/sync.rb
polyphony-0.46.0 lib/polyphony/core/sync.rb
polyphony-0.45.5 lib/polyphony/core/sync.rb