Created
November 27, 2018 09:16
-
-
Save oyakata/3220a1c6fc6d91af7679d29f982bcac6 to your computer and use it in GitHub Desktop.
Goのchannelのclose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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