Goroutine:时间。睡眠或时间。之后

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.

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