Skip to content

Instantly share code, notes, and snippets.

@oyakata
Created November 27, 2018 09:16
Show Gist options
  • Save oyakata/3220a1c6fc6d91af7679d29f982bcac6 to your computer and use it in GitHub Desktop.
Save oyakata/3220a1c6fc6d91af7679d29f982bcac6 to your computer and use it in GitHub Desktop.
Goのchannelのclose
package main
import (
"fmt"
"sync"
"time"
)
func main() {
ch := make(chan string)
var wg sync.WaitGroup
wg.Add(1)
go func() {
//L:
for {
//select {
//case v, ok := <-ch:
// if !ok {
// wg.Done()
// break L // ok
// // return // ok
// // break // ng WaitGroup is reused before previous Wait has returned
// // https://qiita.com/cia_rana/items/a2c3e1609bd25a5c5596
// }
// time.Sleep(time.Second)
// fmt.Println(v)
//}
if v, ok := <-ch; !ok {
wg.Done()
break
} else {
time.Sleep(time.Second)
fmt.Println(v)
}
}
}()
ch <- "=== a ==="
ch <- "=== b ==="
ch <- "=== c ==="
close(ch)
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment