package main
import (
"fmt"
"time"
)
func main() {
done := make(chan struct{})
m1 := msgGen("m1", done)
for i := 0; i < 5; i++ {
if v, ok := timeoutWait(m1, time.Microsecond*500); ok {
fmt.Println(v)
} else {
fmt.Println("m not receive msg")
}
}
done <- struct{}{}
<-done
}
func timeoutWait(c chan string, timeOut time.Duration) (string, bool) {
select {
case m := <-c:
return m, true
case <-time.After(timeOut):
return "", false
}
}
func msgGen(s string, done chan struct{}) chan string {
c := make(chan string)
go func() {
i := 0
for {
select {
case <-time.After(time.Millisecond):
c <- fmt.Sprintf("msger %s receive %d", s, i)
case <-done:
fmt.Println("Cleaning")
time.Sleep(time.Second)
fmt.Println("Clean done")
done <- struct{}{}
return
}
i++
}
}()
return c
}
运行结果:
m not receive msg
msger m1 receive 0
m not receive msg
msger m1 receive 1
m not receive msg
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.msgGen.func1()
C:/Users/Administrator/go/src/go-tour/imooc/180/并发任务的控制/main.go:38 +0xed
created by main.msgGen
C:/Users/Administrator/go/src/go-tour/imooc/180/并发任务的控制/main.go:33 +0xb9
exit status 2
麻烦老师解答下哇,学的一知半解的。