在接收方从通道内拿到所有数据后发送一个done来通知发送方关闭channel
func worker(msg chan string, done chan bool) {
for {
select {
case <-done:
fmt.Println("Done.")
close(msg)
return
default:
msg<-"hello world."
time.Sleep(500*time.Millisecond)
}
}
}
func main() {
msg := make(chan string)
done := make(chan bool)
timeout := time.After(5 * time.Second)
// 将done传入worker 如果main接收完成通知worker关闭msg
// 如果从worker直接关闭 main会继续接收msg的零值
// 如果在main直接关闭 worker会向关闭的channel发送引起panic
go worker(msg, done)
for {
select {
case m := <-msg:
fmt.Println("recieved msg:", m)
case <-timeout:
done <- true
time.Sleep(500 * time.Millisecond)
return
}
}
}
有疑问加站长微信联系(非本文作者)