中断一个睡觉的goroutine? [英] Interrupt a sleeping goroutine?

查看:168
本文介绍了中断一个睡觉的goroutine?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有我可以执行的方式,例如

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

然后当我想要做的时候唤醒睡觉的房间所以?

我看到 Sleep.go中存在 Reset(d持续时间) / code>但我无法调用它..任何想法?

解决方案

没有办法要打断 time.Sleep ,你可以使用 time.After 以及选择语句来获得您所追求的功能。



简单的例子展示了基本的想法:

pre $ package main

导入(
fmt
时间


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

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

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


fmt.Println(你好,游乐场)
}

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



在这个例子中,我们产生了一个信令例程来告诉主要停止暂停。主要是在两个频道, timeoutchan (我们的信号)和 time.After 之后返回的频道收听。当它在这两个频道中的任何一个上收到时,它将跳出选择并继续执行。


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?

解决方案

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 (
    "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")
}

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.

这篇关于中断一个睡觉的goroutine?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆