Skip to content

Instantly share code, notes, and snippets.

@Northern-Lights
Created February 1, 2019 21:48
Show Gist options
  • Save Northern-Lights/1201a1eac2d3dfcb2f56cb91a81be399 to your computer and use it in GitHub Desktop.
Save Northern-Lights/1201a1eac2d3dfcb2f56cb91a81be399 to your computer and use it in GitHub Desktop.
What happens when you fill a channel, close it, then try to recv?
// Q: What happens when you fill a channel, close it, then try to recv?
// A: You can keep reading the values until the buffer is empty, then
// the close operation takes effect
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan struct{}, 3)
fmt.Printf("len: %d cap: %d\n", len(ch), cap(ch))
// fill
for i := 0; i < cap(ch); i++ {
ch <- struct{}{}
}
// close in 25ms
go func() {
time.Sleep(25 * time.Millisecond)
close(ch)
fmt.Println("Closed")
}()
// recv 1 every second; close should have happened before the 1st
for i := 0; i < cap(ch)+1; i++ {
time.Sleep(1000 * time.Millisecond)
_, ok := <-ch
fmt.Println(ok)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment