Issue
incoming := make(chan int)
done := make(chan struct{})
...
close(done)
...
select {
case incoming <- order:
// logic
case <-done:
return
}
Let’s say you close the done channel before the select statement:
1.The case <-done will be selected.
2.Is this because when close(done) executes, the done channel will be in a state, in which the select statement will consider the "case <-done" a match over the writing case "incoming <- order"?
Solution
The select
statement blocks until one or more of the communication operations in its cases
can proceed. As soon as one or more communication operations can proceed select
will randomly choose one of them.
A receive operation on a closed channel
can proceed immediately.
Execution of a "select" statement proceeds in several steps:
- For all the cases in the statement, the channel operands of
receive operations and the channel and right-hand-side expressions
of send statements are evaluated exactly once, in source order,
upon entering the "select" statement. The result is a set of
channels to receive from or send to, and the corresponding values
to send. Any side effects in that evaluation will occur
irrespective of which (if any) communication operation is selected
to proceed. Expressions on the left-hand side of a RecvStmt with a > short variable declaration or assignment are not yet evaluated.- If one or more of the communications can proceed, a single one
that can proceed is chosen via a uniform pseudo-random selection.
Otherwise, if there is a default case, that case is chosen. If
there is no default case, the "select" statement blocks until at
least one of the communications can proceed.- Unless the selected case is the default case, the respective
communication operation is executed.- If the selected case is a RecvStmt with a short variable
declaration or an assignment, the left-hand side expressions are
evaluated and the received value (or values) are assigned.- The statement list of the selected case is executed.
A receive operation on a closed channel can always proceed
immediately, yielding the element type’s zero value after any
previously sent values have been received.
Answered By – mkopriva
Answer Checked By – Candace Johnson (GoLangFix Volunteer)