funcboring(msg string) <-chanstring { // Returns receive-only channel of strings. c := make(chanstring) gofunc() { // We launch the goroutine from inside the function. for i := 0; ; i++ { c <- fmt.Sprintf("%s %d", msg, i) time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) } }() return c // Return the channel to the caller. }
复用channel(select)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcmain() { c := boring("Joe") timeout := time.After(5 * time.Second) timer := time.NewTimer(3 * time.Second) for { select { case s := <-c: fmt.Println(s) case <-timer.C: //定时轮训事情 timer.Reset(3 * time.Second) case <-timeout: // 监听超时信号 fmt.Println("You talk too much.") return case <-quit: // 监听退出信号 return } } }