Skip to content

Commit a3a92e8

Browse files
committed
Fix enq_work behavior when single-threaded
If there's only one thread in the task's preferred thread pool, use that thread's work queue.
1 parent 38727be commit a3a92e8

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

base/task.jl

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -767,22 +767,33 @@ end
767767

768768
function enq_work(t::Task)
769769
(t._state === task_state_runnable && t.queue === nothing) || error("schedule: Task not runnable")
770-
if t.sticky || Threads.threadpoolsize() == 1
770+
771+
# Sticky tasks go into their thread's work queue.
772+
if t.sticky
771773
tid = Threads.threadid(t)
772774
if tid == 0
773-
# Issue #41324
774-
# t.sticky && tid == 0 is a task that needs to be co-scheduled with
775-
# the parent task. If the parent (current_task) is not sticky we must
776-
# set it to be sticky.
777-
# XXX: Ideally we would be able to unset this
778-
current_task().sticky = true
775+
# The task is not yet stuck to a thread. Stick it to the current
776+
# thread and do the same to the parent task (the current task) so
777+
# that the tasks are correctly co-scheduled (issue #41324).
778+
# XXX: Ideally we would be able to unset this.
779779
tid = Threads.threadid()
780780
ccall(:jl_set_task_tid, Cint, (Any, Cint), t, tid-1)
781+
current_task().sticky = true
781782
end
782783
push!(workqueue_for(tid), t)
783784
else
784-
Partr.multiq_insert(t, t.priority)
785-
tid = 0
785+
tp = Threads.threadpool(t)
786+
if Threads.threadpoolsize(tp) == 1
787+
# There's only one thread in the task's assigned thread pool;
788+
# use its work queue.
789+
tid = (tp === :default) ? 1 : Threads.threadpoolsize(:default)+1
790+
ccall(:jl_set_task_tid, Cint, (Any, Cint), t, tid-1)
791+
push!(workqueue_for(tid), t)
792+
else
793+
# Otherwise, put the task in the multiqueue.
794+
Partr.multiq_insert(t, t.priority)
795+
tid = 0
796+
end
786797
end
787798
ccall(:jl_wakeup_thread, Cvoid, (Int16,), (tid - 1) % Int16)
788799
return t

0 commit comments

Comments
 (0)