I wonder what is the better way to do a wait in a goroutine, time.Sleep()
or <-time.After()
? What's the difference between the two and how to make choices? Thanks.
The WaitGroup type of sync package, is used to wait for the program to finish all goroutines launched from the main function. It uses a counter that specifies the number of goroutines, and Wait blocks the execution of the program until the WaitGroup counter is zero.
The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package.
To pause the execution of a current program in Go, delay code execution, and wait for a specified period of time, you just need to use the Sleep() function defined in the time package. As an argument, this function takes a variable of type time.
A goroutine is a lightweight thread managed by the Go runtime. go f(x, y, z) starts a new goroutine running f(x, y, z) The evaluation of f , x , y , and z happens in the current goroutine and the execution of f happens in the new goroutine.
I don't think it matters much for the majority of programs. There has been a question on golang-nuts about this but I don't think one can draw any conclusion.
In practice After
is useful in contexts where one already needs to select
on a number of channels but would also like a timeout:
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.
Again, I don't think it matters in practice but time.Sleep
seems pretty readable so I would go with that.
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
Per go101
The two will both pause the current goroutine execution for a certain duration. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With