Assign closure ownership
Assign closure ownership
If a channel needs closure, one designated owner closes it after all possible sends finish. A single producer usually owns close; multiple producers need coordination. A receiver should not close merely because it no longer wants data.
package main
import ( "fmt" "sync")
func main() { ch := make(chan int) var wg sync.WaitGroup wg.Add(2) for _, v := range []int{4, 9} { go func(v int) { defer wg.Done(); ch <- v }(v) } go func() { wg.Wait(); close(ch) }() sum := 0 for v := range ch { sum += v } fmt.Println(sum)}Done follows each send. A separate coordinator waits and closes; main drains concurrently. Waiting in main before draining would deadlock these unbuffered sends. The sum is independent of arrival order. sync.Once alone cannot coordinate close with all sends.
Expected output:
13One reply without closure
package main
import ( "fmt")
func main() { reply := make(chan int) go func() { reply <- 21 }() fmt.Println(<-reply)}Exactly one receive is expected, so no range or future receive depends on closure. The channel can become unreachable without close. If the contract changes to an unknown count, establish closure or cancellation explicitly.
Expected output:
21Try it locally
Launch three producers sending 10,20,30 once each. Use WaitGroup and a separate closer; drain in main and print count and sum.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Channels 07: Assign closure ownership
Check the lesson objective before moving on.
Who should close a channel shared by multiple senders?
Why drain concurrently with Wait?