From 4084f7ebec63cf9b6a53f3a12df91bbf0c0a4161 Mon Sep 17 00:00:00 2001 From: K Pamnany Date: Fri, 8 Jul 2022 18:47:14 +0000 Subject: [PATCH] Add channel state checks to reduce exceptions In channel iteration and in the `@sync` race check. --- base/channels.jl | 18 +++++++++++------- base/task.jl | 24 +++++++++++++----------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/base/channels.jl b/base/channels.jl index da7b1d24583ca..0cf3b8d799926 100644 --- a/base/channels.jl +++ b/base/channels.jl @@ -493,14 +493,18 @@ function show(io::IO, ::MIME"text/plain", c::Channel) end function iterate(c::Channel, state=nothing) - try - return (take!(c), nothing) - catch e - if isa(e, InvalidStateException) && e.state === :closed - return nothing - else - rethrow() + if isopen(c) || isready(c) + try + return (take!(c), nothing) + catch e + if isa(e, InvalidStateException) && e.state === :closed + return nothing + else + rethrow() + end end + else + return nothing end end diff --git a/base/task.jl b/base/task.jl index 22b9c81c95606..5601fea70a112 100644 --- a/base/task.jl +++ b/base/task.jl @@ -424,19 +424,21 @@ function sync_end(c::Channel{Any}) # Capture all waitable objects scheduled after the end of `@sync` and # include them in the exception. This way, the user can check what was # scheduled by examining at the exception object. - local racy - for r in c - if !@isdefined(racy) - racy = [] + if isready(c) + local racy + for r in c + if !@isdefined(racy) + racy = [] + end + push!(racy, r) end - push!(racy, r) - end - if @isdefined(racy) - if !@isdefined(c_ex) - c_ex = CompositeException() + if @isdefined(racy) + if !@isdefined(c_ex) + c_ex = CompositeException() + end + # Since this is a clear programming error, show this exception first: + pushfirst!(c_ex, ScheduledAfterSyncException(racy)) end - # Since this is a clear programming error, show this exception first: - pushfirst!(c_ex, ScheduledAfterSyncException(racy)) end if @isdefined(c_ex)