【发布时间】:2018-11-19 08:13:35
【问题描述】:
我有一个相当简单的程序,它应该在指定的持续时间(例如,一秒)后自行终止
代码:
package main
import (
"fmt"
"time"
)
func emit(wordChannel chan string, done chan bool) {
defer close(wordChannel)
words := []string{"The", "quick", "brown", "fox"}
i := 0
t := time.NewTimer(1 * time.Second)
for {
select {
case wordChannel <- words[i]:
i++
if i == len(words) {
i = 0
}
// Please ignore the following case
case <-done:
done <- true
// fmt.Printf("Got done!\n")
close(done)
return
case <-t.C:
fmt.Printf("\n\nGot done!\n\n")
return
}
}
}
func main() {
mainWordChannel := make(chan string)
// Please ignore mainDoneChannel
mainDoneChannel := make(chan bool)
go emit(mainWordChannel, mainDoneChannel)
for word := range mainWordChannel {
fmt.Printf("%s ", word)
}
}
我编译执行二进制,你可以看到执行here。
这显然超过 1 秒。
Go 在NewTimer 上的文档是这样写的:
func NewTimer
func NewTimer(d Duration) *TimerNewTimer 创建一个新的 Timer,它将在至少持续时间 d 之后在其通道上发送当前时间。
有人可以帮我理解这里发生了什么吗?为什么程序在 1 秒后没有完全终止(或接近 at least)?
【问题讨论】:
-
老实说,在我看来它可能只运行了一秒钟,但我们一直在看着非常慢的终端滚动。注释掉你的打印,看看它运行了多长时间。
-
在我的机器上测试过了。它工作正常。您主要是在处理缓慢的终端打印。
-
@Thomas 那可能是……
标签: go concurrency channel