Skip to content

Commit dcfad21

Browse files
authored
Add throw option in wait(::Task) (JuliaLang#53685)
As we discussed with @vtjnash in PR JuliaLang#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`.
1 parent a0cee55 commit dcfad21

File tree

3 files changed

+19
-4
lines changed

3 files changed

+19
-4
lines changed

base/condition.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ Block the current task until some event occurs, depending on the type of the arg
113113
* `Process`: Wait for a process or process chain to exit. The `exitcode` field of a process
114114
can be used to determine success or failure.
115115
* [`Task`](@ref): Wait for a `Task` to finish. If the task fails with an exception, a
116-
`TaskFailedException` (which wraps the failed task) is thrown.
116+
`TaskFailedException` (which wraps the failed task) is thrown. Waiting on a task
117+
additionally allows passing `throw=false` which prevents throwing a `TaskFailedException`
118+
when the task fails.
117119
* [`RawFD`](@ref): Wait for changes on a file descriptor (see the `FileWatching` package).
118120
119121
If no argument is passed, the task blocks for an undefined period. A task can only be

base/task.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -356,11 +356,11 @@ function _wait2(t::Task, waiter::Task)
356356
nothing
357357
end
358358

359-
function wait(t::Task)
359+
function wait(t::Task; throw=true)
360360
t === current_task() && error("deadlock detected: cannot wait on current task")
361361
_wait(t)
362-
if istaskfailed(t)
363-
throw(TaskFailedException(t))
362+
if throw && istaskfailed(t)
363+
Core.throw(TaskFailedException(t))
364364
end
365365
nothing
366366
end

test/threads.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,3 +341,16 @@ end
341341
@testset "Base.Threads docstrings" begin
342342
@test isempty(Docs.undocumented_names(Threads))
343343
end
344+
345+
@testset "wait failed task" begin
346+
@testset "wait without throw keyword" begin
347+
t = Threads.@spawn error("Error")
348+
@test_throws TaskFailedException wait(t)
349+
end
350+
351+
@testset "wait with throw=false" begin
352+
t = Threads.@spawn error("Error")
353+
wait(t; throw=false)
354+
@test istaskfailed(t)
355+
end
356+
end

0 commit comments

Comments
 (0)