中断一个睡觉的goroutine? [英] Interrupt a sleeping 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屋!