Stop goroutine execution on timeout

后端 未结 3 1827
萌比男神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条回答
  •  萌比男神i
    2020-12-06 19:22

    There's no good way to "interrupt" the execution of a goroutine in the middle of it's execution.

    Go uses a fork-join model of concurrency, this means that you "fork" creating a new goroutine and then have no control over how that goroutine is scheduled until you get to a "join point". A join point is some kind of synchronisation between more than one goroutine. e.g. sending a value on a channel.

    Taking your specific example, this line:

    ch <- Response{data: "data", status: true}
    

    ... will be able to send the value, no matter what because it's a buffered channel. But the timeout's you've created:

    case <-time.After(50 * time.Millisecond):
      return "Timed out", false
    

    These timeouts are on the "receiver" or "reader" of the channel, and not on the "sender". As mentioned at the top of this answer, there's no way to interrupt the execution of a goroutine without using some synchronisation techniques.

    Because the timeouts are on the goroutine "reading" from the channel, there's nothing to stop the execution of the goroutine that send on the channel.

提交回复
热议问题