英文:
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.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")
}
在这个示例中,我们创建了一个信号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 (
"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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论