Skip to content

Commit

Permalink
add experimental @spawn macro to Base.Threads
Browse files Browse the repository at this point in the history
  • Loading branch information
JeffBezanson committed Jul 20, 2019
1 parent bb8fefb commit 53f717f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
29 changes: 28 additions & 1 deletion base/threadingconstructs.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This file is a part of Julia. License is MIT: https://julialang.org/license

export threadid, nthreads, @threads
export threadid, nthreads, @threads, @spawn

"""
Threads.threadid()
Expand Down Expand Up @@ -102,3 +102,30 @@ macro threads(args...)
throw(ArgumentError("unrecognized argument to @threads"))
end
end

"""
Threads.@spawn expr
Create and run a [`Task`](@ref) on any available thread. To wait for the task to
finish, call [`wait`](@ref) on the result of this macro, or call [`fetch`](@ref)
to wait and then obtain its return value.
!!! note
This feature is currently considered experimental.
!!! compat "Julia 1.3"
This macro is available as of Julia 1.3.
"""
macro spawn(expr)
thunk = esc(:(()->($expr)))
var = esc(Base.sync_varname)
quote
local task = Task($thunk)
task.sticky = false
if $(Expr(:isdefined, var))
push!($var, task)
end
schedule(task)
task
end
end
1 change: 1 addition & 0 deletions doc/src/base/multi-threading.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ described here might (and likely will) change in the future.
Base.Threads.threadid
Base.Threads.nthreads
Base.Threads.@threads
Base.Threads.@spawn
```

```@docs
Expand Down
4 changes: 1 addition & 3 deletions test/threads_exec.jl
Original file line number Diff line number Diff line change
Expand Up @@ -647,9 +647,7 @@ function pfib(n::Int)
if n <= 1
return n
end
t = @task pfib(n-2)
t.sticky = false
schedule(t)
t = @spawn pfib(n-2)
return pfib(n-1) + fetch(t)::Int
end
@test pfib(20) == 6765
Expand Down

0 comments on commit 53f717f

Please sign in to comment.