From bc462b7969bf21471b4767af02d497c772dcc12c Mon Sep 17 00:00:00 2001 From: Julien Portalier Date: Mon, 12 May 2025 14:48:18 +0200 Subject: [PATCH] Fix: calling Fiber::ExecutionContext#enqueue from bare Thread A bare thread doesn't have an execution context, yet may be capable to call Fiber#enqueue to enqueue a fiber back into its original context. --- src/fiber/execution_context.cr | 7 ++++++- src/fiber/execution_context/multi_threaded.cr | 2 +- src/fiber/execution_context/single_threaded.cr | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/fiber/execution_context.cr b/src/fiber/execution_context.cr index 1c1ae2f1eb21..8d2289740ebc 100644 --- a/src/fiber/execution_context.cr +++ b/src/fiber/execution_context.cr @@ -122,6 +122,10 @@ module Fiber::ExecutionContext Thread.current.execution_context end + def self.current? : ExecutionContext? + Thread.current.execution_context? + end + # :nodoc: # # Tells the current scheduler to suspend the current fiber and resume the @@ -181,6 +185,7 @@ module Fiber::ExecutionContext # # Enqueues a fiber to be resumed inside the execution context. # - # May be called from any ExecutionContext (i.e. must be thread-safe). + # May be called from any ExecutionContext (i.e. must be thread-safe). May also + # be called from bare threads (outside of an ExecutionContext). abstract def enqueue(fiber : Fiber) : Nil end diff --git a/src/fiber/execution_context/multi_threaded.cr b/src/fiber/execution_context/multi_threaded.cr index 9793c5468b0b..e843178d1d10 100644 --- a/src/fiber/execution_context/multi_threaded.cr +++ b/src/fiber/execution_context/multi_threaded.cr @@ -180,7 +180,7 @@ module Fiber::ExecutionContext # :nodoc: def enqueue(fiber : Fiber) : Nil - if ExecutionContext.current == self + if ExecutionContext.current? == self # local enqueue: push to local queue of current scheduler ExecutionContext::Scheduler.current.enqueue(fiber) else diff --git a/src/fiber/execution_context/single_threaded.cr b/src/fiber/execution_context/single_threaded.cr index 74ad81ea51ce..f4a2aa4f3694 100644 --- a/src/fiber/execution_context/single_threaded.cr +++ b/src/fiber/execution_context/single_threaded.cr @@ -102,7 +102,7 @@ module Fiber::ExecutionContext # :nodoc: def enqueue(fiber : Fiber) : Nil - if ExecutionContext.current == self + if ExecutionContext.current? == self # local enqueue Crystal.trace :sched, "enqueue", fiber: fiber @runnables.push(fiber)