Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: context: add Sleep #39483

Closed
dolmen opened this issue Jun 9, 2020 · 2 comments
Closed

proposal: context: add Sleep #39483

dolmen opened this issue Jun 9, 2020 · 2 comments

Comments

@dolmen
Copy link
Contributor

dolmen commented Jun 9, 2020

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

@gopherbot gopherbot added this to the Proposal milestone Jun 9, 2020
@mvdan
Copy link
Member

mvdan commented Jun 9, 2020

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.

@dolmen dolmen closed this as completed Jun 9, 2020
@dolmen
Copy link
Contributor Author

dolmen commented Jun 11, 2020

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.

@golang golang locked and limited conversation to collaborators Jun 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants