中断睡觉的goroutine?

Ani*_*edi 6 go

例如,有没有办法可以执行

time.Sleep(time.Second * 5000) //basically a long period of time
Run Code Online (Sandbox Code Playgroud)

然后在我愿意的时候"唤醒"睡觉的goroutine?

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

Gre*_*reg 21

没有办法打断a time.Sleep,但是,你可以使用time.After,并select声明你获得的功能.

举例说明基本思路:

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")
}
Run Code Online (Sandbox Code Playgroud)

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

在这个例子中,我们正在产生一个信令goroutine告诉main停止暂停.主要是等待和聆听两个通道,timeoutchan(我们的信号)和返回的通道time.After.当它在这些通道中的任何一个上接收时,它将脱离选择并继续执行.