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

fengweiqiang · · 2247 次点击
可以用runtime.Goexit()停止当前Go协程 ``` package main import ( "log" "runtime" "time" ) func main() { cb := make(chan bool, 1) go func() { timer2 := time.NewTimer(time.Second * 3) tick := time.Tick(time.Second * 5) select { case <-timer2.C: runtime.Goexit() //超时后退出该Go协程 case <-tick: //模拟超时任务 log.Println(222) //处理业务代码 cb <- true 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) } ```
#4
更多评论
```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