go-concurrency101/5-close-channels/main.go

71 lines
1010 B
Go
Raw Normal View History

package main
import (
"fmt"
"time"
)
/*
@Ref: https://livebook.manning.com/book/go-in-practice/chapter-3/65
*/
func main() {
msg := make(chan string)
done := make(chan bool)
until := time.After(5 * time.Second)
go send(msg, done)
for {
select {
case m := <-msg:
fmt.Println(m)
case <-until:
done <- true
time.Sleep(500 * time.Millisecond)
return
}
}
}
func send(ch chan<- string, done <-chan bool) {
for {
select {
case <-done:
fmt.Println("done")
close(ch)
return
default:
ch <- "Hello"
time.Sleep(500 * time.Millisecond)
}
}
}
// Improper channel close
// func main() {
// msg := make(chan string)
// until := time.After(5 * time.Second)
// go send(msg)
// for {
// select {
// case m := <-msg:
// fmt.Println(m)
// case <-until:
// close(msg)
// time.Sleep(500 * time.Millisecond)
// return
// }
// }
// }
// func send(ch chan string) {
// for {
// ch <- "hello"
// time.Sleep(500 * time.Millisecond)
// }
// }