定时器
1 time.After不要直接用在select case后面,
package main import ( "fmt" "time" ) func test(){ ch <- 3 } var ch chan int func main(){ ch = make(chan int, 1) timeout := time.After(time.Second * 3) go test() for{ select{ case <- ch: fmt.Println("kkk") continue // 注意这里的timeout不能写成time.After,否则每次过来都会重新计时,在这个程序中相当于死循环了 case <- timeout: fmt.Println("协程超时") } break } }
参考:https://studygolang.com/articles/10229