Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Goroutine: time.Sleep or time.After

Tags:

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.

like image 209
J Freebird Avatar asked Jun 17 '16 22:06

J Freebird


People also ask

How do you wait for a Goroutine to finish?

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.

What is Go sleep time?

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.

How do you sleep in Go program?

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.

What is a Goroutine?

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.


2 Answers

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
like image 112
cnicutar Avatar answered Oct 03 '22 22:10

cnicutar


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.

like image 24
zangw Avatar answered Oct 03 '22 22:10

zangw