Skip to content

Commit

Permalink
Add a threadpool=:default parameter to Channel constructor
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kpamnany committed Aug 9, 2023
1 parent d99f249 commit 76d40e1
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions base/channels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand All @@ -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
Expand Down

0 comments on commit 76d40e1

Please sign in to comment.