Skip to content

proposal: allow send on a closed channel to gracefully fail in a select #15411

Closed
@OneOfOne

Description

@OneOfOne

Currently, the only way to close a channel with multiple writers is to use a hacky defer func() { recover() }() or using a waitgroup and a counter.

My proposal is to allow something like this to work without the hack:

func SendVal(ch chan *Val, closeCh chan struct{}, v *Val) (ok bool) {
    select {
    case <-closeCh:
        return false
    case ch <- v:
        return true
    }
}

It should still panic without the select, or an alternative syntax but I know this is highly unlikely in the 1.x cycle.

func SendVal(ch chan *Val, closeCh chan struct{}, v *Val) (ok bool) {
    ok = ch <- v
    return
}

This is not about allowing multiple writers to close a channel, this is about allowing a closed channel in a multiple select situation.

closed <- v
// and
select {
case closed <- v:
}

Should still panic, however:

select {
case closed <- v:
case <-anotherCh:
}

Wouldn't panic (check the CL and the test in it).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions