怎么实现真正的goroutine超时?

lipengfeihb · · 1342 次点击
```go package main import ( "fmt" "time" ) const timeoutSecond = time.Second * 5 func handleTask() <-chan string { //receive channel ch := make(chan string) go func() { time.Sleep(time.Second * 6) //mock produce time-consuming ch <- "Finish" }() return ch } func main() { for { select { case msg := <-handleTask(): fmt.Print(msg) case <-time.After(timeoutSecond): fmt.Print("Timeout") return } } } ```
#5
更多评论
第一点 我感觉你超时的用法有点错误了。 cancleFun()这个函数在你的代码中是无效的。这个函数的作用只有通知ctx.Done。而你使用WithTimeout倒计时结束后也会通知ctx.Done(). 第二点 超时结束不是程序就马上结束。你需要在代码层面进行处理才能结束,实际上他只有一个通知ctx.Done一个功能。 如果你想让你的goroutine在超时的时候结束,也很简单,主函数中相似的逻辑 实现在 goroutine中就可以了。 ``` //处理任务 func handleTask(ctx context.Context, ch chan bool, taskId int) { for i := 0; i < 5; i++ { select { case <-ctx.Done(): return default: time.Sleep(time.Second) fmt.Println(fmt.Sprintf("处理任务 %d:%d, %v", taskId, i, time.Now())) } } ch <- true } ```
#1
第一点认同。 第二点 感觉不太好实现,生产环境下handleTask()是没有for 的,都是串行的处理逻辑,没有合适的位置来监听ctx.Done()。
#2