Stop goroutine execution on timeout

后端 未结 3 1825
萌比男神i
萌比男神i 2020-12-06 18:50

I want to stop goroutine execution on timeout. But it seems like it is not working for me. I am using iris framework.

  type Response struct {
          


        
3条回答
  •  既然无缘
    2020-12-06 19:33

    You have a gouroutine leaks, you must handle some done action to return the goroutine before timeout like this:

    func (s *CicService) Find() (interface{}, bool) {
    
        ch := make(chan Response, 1)
        done := make(chan struct{})
        go func() {
            select {
            case <-time.After(10 * time.Second):
            case <-done:
                return
            }
            fmt.Println("test")
            fmt.Println("test1")
            ch <- Response{data: "data", status: true}
        }()
        select {
        case res := <-ch:
            return res.data, res.status
        case <-time.After(50 * time.Millisecond):
            done <- struct{}{}
            return "Timed out", false
        }
    
    }
    

提交回复
热议问题