英文:
How to break out of time.Sleep
问题
我几天前刚开始学习Golang,但是我似乎无法弄清楚如何跳出time.Sleep()...
我可以跳出for循环,但是函数不会返回,因为Sleep继续执行。
我猜解决方案应该很简单,但我找不到答案。
func main() {
ticker := time.NewTicker(time.Second * 1)
go func() {
for i := range ticker.C {
fmt.Println("tick", i)
ticker.Stop()
break
}
}()
time.Sleep(time.Second * 10)
ticker.Stop()
fmt.Println("Hello, playground")
}
提前感谢!
英文:
I just started picking up Golang a couple days ago and I can't seem to figure out to break out of time.Sleep()...
I can return / break out of the for loop, but the function wont return since Sleep continues doing its thing.
I am guessing the solution is pretty simple, but I can't seem to find the answer.
func main() {
ticker := time.NewTicker(time.Second * 1)
go func() {
for i := range ticker.C {
fmt.Println("tick", i)
ticker.Stop()
break
}
}()
time.Sleep(time.Second * 10)
ticker.Stop()
fmt.Println("Hello, playground")
}
Thanks in advance!
答案1
得分: 6
看起来你想给主 goroutine 发送一条消息,告诉它你的另一个 goroutine 已经完成。为此,使用通道是最好的方法。
func main() {
ticker := time.NewTicker(time.Second)
done := make(chan bool, 1)
go func() {
for i := range ticker.C {
fmt.Println("tick", i)
ticker.Stop()
break
}
done <- true
}()
timer := time.NewTimer(time.Second/2)
select {
case <-done:
timer.Stop()
case <-timer.C:
ticker.Stop()
}
fmt.Println("Done")
}
工作示例:http://play.golang.org/p/5NFsvC5f7P
当计时器大于 ticker 时,它会进行滴答。当计时器小于 ticker 时,你只会看到 "Done"。
英文:
It sounds like you want to send the main goroutine a message telling it your other goroutine is complete. For that, channels are the best way to go.
func main() {
ticker := time.NewTicker(time.Second)
done := make(chan bool, 1)
go func() {
for i := range ticker.C {
fmt.Println("tick", i)
ticker.Stop()
break
}
done <- true
}()
timer := time.NewTimer(time.Second/2)
select {
case <-done:
timer.Stop()
case <-timer.C:
ticker.Stop()
}
fmt.Println("Done")
}
Working example at http://play.golang.org/p/5NFsvC5f7P
When the timer is greater than ticker, it ticks. When it is less than, all you see is "done".
答案2
得分: -2
这可能不是一个非常具体的解决方案,但你可以尝试应用它。
我理解的方式是,你需要在特定条件下跳出计时器。
尝试在你的 sleep 函数周围放置一个 while 循环,并让它每秒钟睡眠一次。
将条件设置为你的函数中的一个布尔值:
while (condition_to_sleep)
{
time.Sleep(1000);
}
这样,当你需要时就可以跳出计时器。
希望能对你有所帮助
英文:
This might not be a very specific solution, but you may be able to apply it.
The way I understand it, is that you need to break out of the timer under a specific condition.
try to put a while loop around your sleep and make it sleep for a second
Set the condition as a bool on your func
while (condition_to_sleep)
{
time.Sleep(1000);
}
This way you can break out of the timer when you need to
Hope this help
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论