Skip to content

Commit

Permalink
Add thread safety to Fiber::StackPool
Browse files Browse the repository at this point in the history
  • Loading branch information
ysbaddaden committed Jan 7, 2025
1 parent b2276f9 commit 7b11dcc
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/fiber/stack_pool.cr
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Fiber
# pointer value) rather than downwards, so *protect* must be false.
def initialize(@protect : Bool = true)
@deque = Deque(Void*).new
@lock = Crystal::SpinLock.new
end

def finalize
Expand All @@ -25,7 +26,7 @@ class Fiber
# returning memory to the operating system.
def collect(count = lazy_size // 2) : Nil
count.times do
if stack = @deque.shift?
if stack = @lock.sync { @deque.shift? }
Crystal::System::Fiber.free_stack(stack, STACK_SIZE)
else
return
Expand All @@ -42,7 +43,7 @@ class Fiber

# Removes a stack from the bottom of the pool, or allocates a new one.
def checkout : {Void*, Void*}
if stack = @deque.pop?
if !@deque.empty? && (stack = @lock.sync { @deque.pop? })
Crystal::System::Fiber.reset_stack(stack, STACK_SIZE, @protect)
else
stack = Crystal::System::Fiber.allocate_stack(STACK_SIZE, @protect)
Expand All @@ -52,7 +53,7 @@ class Fiber

# Appends a stack to the bottom of the pool.
def release(stack) : Nil
@deque.push(stack)
@lock.sync { @deque.push(stack) }
end

# Returns the approximated size of the pool. It may be equal or slightly
Expand Down

0 comments on commit 7b11dcc

Please sign in to comment.