本文介绍了超时时停止执行goroutine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在超时时停止执行goroutine.但这似乎对我不起作用.我正在使用iris框架.

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 {
    data   interface{}
    status bool
  }

  func (s *CicService) Find() (interface{}, bool) {

    ch := make(chan Response, 1)

    go func() {
      time.Sleep(10 * time.Second)

      fmt.Println("test")
      fmt.Println("test1")

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

    select {
    case <-ch:
      fmt.Println("Read from ch")
      res := <-ch
      return res.data, res.status
    case <-time.After(50 * time.Millisecond):
      return "Timed out", false
    }

  }

输出:

 Timed out
 test
 test1

预期输出:

 Timed out

有人可以指出这里缺少什么吗?它确实超时,但仍运行goroutine来打印testtest1.我只想在超时后立即停止执行goroutine.

Can somebody point out what is missing here? It does timeout but still runs goroutine to print test and test1. I just want to stop the execution of goroutine as soon as there is timeout.

推荐答案

没有一种好的方法可以在执行过程中中断" goroutine的执行.

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

Go使用并发的fork-join模型,这意味着您分叉"创建了一个新的goroutine,然后无法控制该goroutine的调度方式,直到到达"join point"为止.连接点是多个goroutine之间的某种同步.例如在通道上发送值.

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

这些超时位于通道的接收器"或读取器"上,而不是位于发送者"上.如答案顶部所述,不使用某些同步技术就无法中断goroutine的执行.

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.

由于超时是在goroutine从通道读取"中进行的,因此没有什么可以阻止在通道上发送的goroutine的执行.

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.

这篇关于超时时停止执行goroutine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:50
查看更多