[英]Goroutine: time.Sleep or time.After
I wonder what is the better way to do a wait in a goroutine, time.Sleep()
or <-time.After()
?我想知道在 goroutine、
time.Sleep()
或<-time.After()
等待的更好方法是什么? What's the difference between the two and how to make choices?两者有什么区别,如何选择? Thanks.
谢谢。
I don't think it matters much for the majority of programs.我认为这对大多数程序来说并不重要。 There has been aquestion on golang-nuts about this but I don't think one can draw any conclusion.
关于这一点,在 golang-nuts 上有一个问题,但我认为人们无法得出任何结论。
In practice After
is useful in contexts where one already needs to select
on a number of channels but would also like a timeout:在实践中
After
在已经需要在多个通道上进行select
但还想要超时的情况下很有用:
select {
case c := <-someChan:
..
case c := <-otherChan:
..
case <-time.After(time.Second * 42):
}
By superficially looking at the code Sleep
seems simpler while After
builds a new timer, with a period, a closure to send the time when it finishes etc.从表面上看代码
Sleep
似乎更简单,而After
构建了一个新的计时器,带有一个句点,一个关闭以在它完成时发送时间等。
Again, I don't think it matters in practice but time.Sleep
seems pretty readable so I would go with that.再说一次,我认为这在实践中并不重要,但
time.Sleep
看起来很可读,所以我time.Sleep
。
On my implementation both of them perform the exact same system calls and end up waiting:在我的实现中,它们都执行完全相同的系统调用并最终等待:
futex(??, FUTEX_WAIT, 0, {41, 999892351}
^^ 41 seconds and change
The two will both pause the current goroutine execution for a certain duration.
两者都会暂停当前的 goroutine 执行一段时间。 The difference is the function call time.Sleep(d) will let the current goroutine enter sleeping sub-state, but still stay in running state, whereas, the channel receive operation <-time.After(d) will let the current goroutine enter blocking state.
不同之处在于函数调用 time.Sleep(d) 会让当前 goroutine 进入 sleep 子状态,但仍保持运行状态,而 channel 接收操作 <-time.After(d) 会让当前 goroutine 进入阻塞状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.