Skip to content

Commit

Permalink
Add throw option in wait(::Task) (#53685)
Browse files Browse the repository at this point in the history
As we discussed with @vtjnash in PR #53341, it might be useful to
introduce the `throw` option in the `wait` function for `Task`. If
`throw=false` is specified, `wait` behaves like `_wait`; it prevents
throwing a `TaskFailedException`.
  • Loading branch information
mrkn authored Mar 11, 2024
1 parent a0cee55 commit dcfad21
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
4 changes: 3 additions & 1 deletion base/condition.jl
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ Block the current task until some event occurs, depending on the type of the arg
* `Process`: Wait for a process or process chain to exit. The `exitcode` field of a process
can be used to determine success or failure.
* [`Task`](@ref): Wait for a `Task` to finish. If the task fails with an exception, a
`TaskFailedException` (which wraps the failed task) is thrown.
`TaskFailedException` (which wraps the failed task) is thrown. Waiting on a task
additionally allows passing `throw=false` which prevents throwing a `TaskFailedException`
when the task fails.
* [`RawFD`](@ref): Wait for changes on a file descriptor (see the `FileWatching` package).
If no argument is passed, the task blocks for an undefined period. A task can only be
Expand Down
6 changes: 3 additions & 3 deletions base/task.jl
Original file line number Diff line number Diff line change
Expand Up @@ -356,11 +356,11 @@ function _wait2(t::Task, waiter::Task)
nothing
end

function wait(t::Task)
function wait(t::Task; throw=true)
t === current_task() && error("deadlock detected: cannot wait on current task")
_wait(t)
if istaskfailed(t)
throw(TaskFailedException(t))
if throw && istaskfailed(t)
Core.throw(TaskFailedException(t))
end
nothing
end
Expand Down
13 changes: 13 additions & 0 deletions test/threads.jl
Original file line number Diff line number Diff line change
Expand Up @@ -341,3 +341,16 @@ end
@testset "Base.Threads docstrings" begin
@test isempty(Docs.undocumented_names(Threads))
end

@testset "wait failed task" begin
@testset "wait without throw keyword" begin
t = Threads.@spawn error("Error")
@test_throws TaskFailedException wait(t)
end

@testset "wait with throw=false" begin
t = Threads.@spawn error("Error")
wait(t; throw=false)
@test istaskfailed(t)
end
end

0 comments on commit dcfad21

Please sign in to comment.