Skip to content

Implement semaphore using linked list. #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 4, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions lib/async/semaphore.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Released under the MIT License.
# Copyright, 2018-2022, by Samuel Williams.

require_relative 'list'

module Async
# A synchronization primitive, which limits access to a given resource.
# @public Since `stable-v1`.
Expand All @@ -12,7 +14,7 @@ class Semaphore
def initialize(limit = 1, parent: nil)
@count = 0
@limit = limit
@waiting = []
@waiting = List.new

@parent = parent
end
Expand Down Expand Up @@ -73,26 +75,34 @@ def acquire
def release
@count -= 1

while (@limit - @count) > 0 and fiber = @waiting.shift
if fiber.alive?
Fiber.scheduler.resume(fiber)
end
while (@limit - @count) > 0 and node = @waiting.first
node.resume
end
end

private

class FiberNode < List::Node
def initialize(fiber)
@fiber = fiber
end

def resume
if @fiber.alive?
Fiber.scheduler.resume(@fiber)
end
end
end

private_constant :FiberNode

# Wait until the semaphore becomes available.
def wait
fiber = Fiber.current
return unless blocking?

if blocking?
@waiting << fiber
@waiting.stack(FiberNode.new(Fiber.current)) do
Fiber.scheduler.transfer while blocking?
end
rescue Exception
@waiting.delete(fiber)
raise
end
end
end