Go: proposal: context: add Sleep

Created on 9 Jun 2020  路  2Comments  路  Source: golang/go

In the context package a Sleep(Context, time.Duration) function would be useful as a tool to migrate code that uses time.Sleep to be aware of context cancellation.

// before
time.Sleep(1*time.Second)
// after
context.Sleep(ctx, 1*time.Second)

Why add it to the stdlib:

  • a simple function that when used should improve readability of code that justs pauses a goroutine.
  • context is the place users should expect such tool
  • no risk of API liability problems as the signature is straightforward

Here is a naive implementation:

func Sleep(ctx context.Context, delay time.Duration) {
    timeoutCtx, cancel := context.WithTimeout(ctx, delay)
    defer cancel()
    <-timeoutCtx.Done()
}

See an example running on the Go Playground

Proposal

Most helpful comment

I'm not sure if I follow. You're arguing that people should be able to write

context.Sleep(ctx, time.Second)

However, they could pretty easily just write:

select {
case <-time.After(time.Second):
case <-ctx.Done():
    // probably early return here
}

You can argue that the select is more lines, but I would argue that you need them anyway, because the code should handle context cancellation by stopping work instead of continuing as normal.

All 2 comments

I'm not sure if I follow. You're arguing that people should be able to write

context.Sleep(ctx, time.Second)

However, they could pretty easily just write:

select {
case <-time.After(time.Second):
case <-ctx.Done():
    // probably early return here
}

You can argue that the select is more lines, but I would argue that you need them anyway, because the code should handle context cancellation by stopping work instead of continuing as normal.

A pure Sleep function without return value isn't that useful.

A more useful signature would return a boolean telling if the timeout has been reached or if the context has been canceled. In that case the name Sleep is not appropriate as the signature doesn't match time.Sleep. So this is not the right proposal.

So, closed.

Was this page helpful?
0 / 5 - 0 ratings