From 76d40e121c561d9747490467ee9b154a0892218b Mon Sep 17 00:00:00 2001 From: K Pamnany Date: Wed, 9 Aug 2023 12:08:01 -0400 Subject: [PATCH] Add a `threadpool=:default` parameter to `Channel` constructor Without this, the task created by a `Channel` will run in the threadpool of the creating task; in the REPL, this could be the interactive threadpool. With this, the `:default` threadpool is used instead, and that behavior can be overridden. --- base/channels.jl | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/base/channels.jl b/base/channels.jl index 1b5b427f92671..8fb049cd1ebd8 100644 --- a/base/channels.jl +++ b/base/channels.jl @@ -59,7 +59,7 @@ Channel(sz=0) = Channel{Any}(sz) # special constructors """ - Channel{T=Any}(func::Function, size=0; taskref=nothing, spawn=false) + Channel{T=Any}(func::Function, size=0; taskref=nothing, spawn=false, threadpool=:default) Create a new task from `func`, bind it to a new channel of type `T` and size `size`, and schedule the task, all in a single call. @@ -70,9 +70,12 @@ The channel is automatically closed when the task terminates. If you need a reference to the created task, pass a `Ref{Task}` object via the keyword argument `taskref`. -If `spawn = true`, the Task created for `func` may be scheduled on another thread +If `spawn=true`, the `Task` created for `func` may be scheduled on another thread in parallel, equivalent to creating a task via [`Threads.@spawn`](@ref). +The `threadpool` argument is used if `spawn=true`, to spawn the new Task to the +specified threadpool. + Return a `Channel`. # Examples @@ -117,6 +120,9 @@ true In earlier versions of Julia, Channel used keyword arguments to set `size` and `T`, but those constructors are deprecated. +!!! compat "Julia 1.9" + The `threadpool=` parameter was added in Julia 1.9. + ```jldoctest julia> chnl = Channel{Char}(1, spawn=true) do ch for c in "hello world" @@ -129,12 +135,13 @@ julia> String(collect(chnl)) "hello world" ``` """ -function Channel{T}(func::Function, size=0; taskref=nothing, spawn=false) where T +function Channel{T}(func::Function, size=0; taskref=nothing, spawn=false, threadpool=:default) where T chnl = Channel{T}(size) task = Task(() -> func(chnl)) task.sticky = !spawn bind(chnl, task) if spawn + Base.Threads._spawn_set_thrpool(task, threadpool) schedule(task) # start it on (potentially) another thread else yield(task) # immediately start it, yielding the current thread