计时器通道 – 在循环内部输出stdout

huangapple go评论77阅读模式
英文:

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:=&lt;-t.C
		fmt.Print(&quot;%T&quot;,k)
		fmt.Println(&quot;poet&quot;)
	}
}

Somehow, when I remove the below two lines , the program works fine

k:=&lt;-t.C
fmt.Print(&quot;%T&quot;,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:=&lt;-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)
    &lt;- timer.C
    println(&quot;Timer expired&quot;)
}

答案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 (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	now := time.Now()
	timeElapsed := true
	for timeElapsed {
		fmt.Println(&quot;poet&quot;)
		timeElapsed = (time.Since(now) &lt; (1 * time.Second))
	}
	fmt.Println(&quot;Times up!&quot;)
}

huangapple
  • 本文由 发表于 2016年10月27日 18:17:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/40282024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定