中断一个正在睡眠的 goroutine?

huangapple go评论99阅读模式
英文:

Interrupt a sleeping goroutine?

问题

有没有一种方法可以执行,例如

time.Sleep(time.Second * 5000) //基本上是一个很长的时间

然后在我希望的时候“唤醒”正在睡眠的goroutine?

我看到在Sleep.go中有一个Reset(d Duration),但我无法调用它.. 有什么想法吗?

英文:

Is there a way in which I can execute, for example

time.Sleep(time.Second * 5000) //basically a long period of time

and then "wake up" the sleeping goroutine when I wish to do so?

I saw that there is a Reset(d Duration) in Sleep.go but I'm unable to invoke it.. Any thoughts?

答案1

得分: 38

没有办法中断time.Sleep,但是你可以利用time.Afterselect语句来实现你想要的功能。

下面是一个简单的示例,展示了基本的思路:

package main

import (
    "fmt"
    "time"
)

func main() {
    timeoutchan := make(chan bool)

    go func() {
        <-time.After(2 * time.Second)
        timeoutchan <- true
    }()

    select {
    case <-timeoutchan:
        break
    case <-time.After(10 * time.Second):
        break
    }

    fmt.Println("Hello, playground")
}

在这个示例中,我们创建了一个信号goroutine来告诉主goroutine停止暂停。主goroutine在两个通道上等待和监听,timeoutchan(我们的信号)和time.After返回的通道。当它从这两个通道中的任意一个接收到数据时,它将跳出select语句并继续执行。

英文:

There isn't a way to interrupt a time.Sleep, however, you can make use of time.After, and a select statement to get the functionality you're after.

Simple example to show the basic idea:

package main

import (
    &quot;fmt&quot;
    &quot;time&quot;
)

func main() {
    timeoutchan := make(chan bool)

    go func() {
        &lt;-time.After(2 * time.Second)
        timeoutchan &lt;- true
    }()

    select {
    case &lt;-timeoutchan:
        break
    case &lt;-time.After(10 * time.Second):
        break
    }

    fmt.Println(&quot;Hello, playground&quot;)
}

http://play.golang.org/p/7uKfItZbKG

In this example, we're spawning a signalling goroutine to tell main to stop pausing. The main is waiting and listening on two channels, timeoutchan (our signal) and the channel returned by time.After. When it receives on either of these channels, it will break out of the select and continue execution.

huangapple
  • 本文由 发表于 2014年4月28日 09:55:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/23331370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定