go协程超时后怎么中断协程执行的任务

fengweiqiang · · 2231 次点击
可以结合context.WithTimeout去停止goroutine
#5
更多评论
```go package main import ( "log" "time" ) func main() { cb := make(chan bool, 1) go func() { timer2 := time.NewTimer(time.Second * 5) select { case <-timer2.C: log.Println(222) cb <- true case <-cb: return } }() log.Println() timer := time.NewTimer(time.Second * 2) select { case <-timer.C: log.Println("time out") cb <- false case tmp := <-cb: log.Println(tmp) } time.Sleep(time.Second * 10) log.Println(123) } ```
#1
timer2 再定义一个的话没法执行逻辑代码吧![3.png](https://static.studygolang.com/190925/00dc87f4e4fe9d54ae393163943b5fa5.png)
#2