Skip to content

Commit

Permalink
Fix: per-thread stack-pool for ExecutionContext::MultiThreaded
Browse files Browse the repository at this point in the history
The current Fiber releases the dying fiber's stack to the pool before it
switches context to another fiber, which means there is a time window
during which a scheduler may pick the stack and start a new fiber while
another scheduler still hasn't switched context, which will corrupt the
stack.
  • Loading branch information
ysbaddaden committed Mar 11, 2024
1 parent aba30c6 commit 048888f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/multi_threaded.cr
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ abstract class ExecutionContext
getter? idle : Bool = false

protected getter global_queue : GlobalQueue = GlobalQueue.new
getter stack_pool : Fiber::StackPool = Fiber::StackPool.new

# :nodoc:
def self.default(size : Int32) : self
Expand Down Expand Up @@ -96,6 +95,11 @@ abstract class ExecutionContext
unpark_idle_thread
end

# TODO: there should be one stack pool per execution context (not per scheduler)
def stack_pool : Fiber::StackPool
raise "BUG: call #{self.class.name}#Scheduler#stack_pool instead of {self.class.name}#stack_pool"
end

# TODO: there should be one event loop per execution context (not per scheduler)
def event_loop : Crystal::EventLoop
raise "BUG: call #{self.class.name}#Scheduler#event_loop instead of #{self.class.name}#event_loop"
Expand Down
4 changes: 3 additions & 1 deletion src/multi_threaded/scheduler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ abstract class ExecutionContext

# :nodoc:
def stack_pool : Fiber::StackPool
@execution_context.stack_pool
# TODO: there should be one stack pool per execution context
# @execution_context.stack_pool
@stack_pool ||= Fiber::StackPool.new
end

# Unlike `ExecutionContext::MultiThreaded#enqueue` this method is only
Expand Down

0 comments on commit 048888f

Please sign in to comment.