英文:
Timer Channel - Issue stdout inside loop
问题
我创建了一个无限循环来打印“poet”,但在控制台中没有打印任何内容。
func main() {
    t := time.NewTimer(1 * time.Minute)
    for {
        k := <-t.C
        fmt.Print("%T", k)
        fmt.Println("poet")
    }
}
不知何故,当我删除下面两行时,程序就正常工作了。
k := <-t.C
fmt.Print("%T", k)
我是一个Golang的新手,请帮助我理解是什么原因导致了这个问题。谢谢。
英文:
I created an infinite loop to print "poet" but doesn't print anything in the console.
func main() {
	t := time.NewTimer(1 * time.Minute)
	for {
		k:=<-t.C
		fmt.Print("%T",k)
		fmt.Println("poet")
	}
}
Somehow, when I remove the below two lines , the program works fine
k:=<-t.C
fmt.Print("%T",k)
I am a newbie in Golang, please help me to understand what is causing this issue.Thank you
答案1
得分: 2
Timer 类型表示一个单一事件,所以当它在这里发生时 k:=<-t.C,你会遇到死锁 - 因为所有的 Go 协程都处于休眠状态,你将永远无法在循环中获得另一个时间值。
下面是使用 Timer 的示例,也许你想使用 Ticker 代替?
func main() {
    timer := time.NewTimer(time.Second * 2)
    <- timer.C
    println("Timer expired")
}
英文:
The Timer type represents a single event,
so when it happen here
k:=<-t.C
you got deadlock - as all go-routines are asleep and you'll never get another time value inside the loop.
Below is example of using Timer, perhaps you wanted to use Ticker instead?
func main() {
    timer := time.NewTimer(time.Second * 2)
    <- timer.C
    println("Timer expired")
}
答案2
得分: 0
这将打印出'poet'直到时间到期。
package main
import (
	"fmt"
	"time"
)
func main() {
	now := time.Now()
	timeElapsed := true
	for timeElapsed {
		fmt.Println("poet")
		timeElapsed = (time.Since(now) < (1 * time.Second))
	}
	fmt.Println("时间到!")
}
英文:
This will print 'poet' until the time expires.
package main
import (
	"fmt"
	"time"
)
func main() {
	now := time.Now()
	timeElapsed := true
	for timeElapsed {
		fmt.Println("poet")
		timeElapsed = (time.Since(now) < (1 * time.Second))
	}
	fmt.Println("Times up!")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论