Detachable context.Context?

267 views
Skip to first unread message

Alex Besogonov

unread,
Sep 3, 2022, 11:56:19 AM9/3/22
to golang-nuts
Hi!

Let me give you some context. context.Context in Go serves two main purposes:
1. Cancellation and timeout support.
2. A carrier of values, as a de-facto replacement for thread-local variables.

I have a problem with the first item. Cancellation and timeouts automatically propagate to child contexts, which is usually a good thing. However, sometimes it would be nice to be able to create child contexts that share only values but not the timeout/cancellation.

Typically it's needed if the code wants to start a background goroutine to do some work. E.g. in pseudocode:

func StartConnection(ctx context.Context, addr string) (err error) {
  conn, err = net.DialWithContext(ctx, addr)
  if err != nil { return err; }
  go heartbeatFunc(ctx, conn);
...
}

Right now it's not possible to do that cleanly. The only way is to create a brand new context and copy all the needed values. Which requires the code to know which values might be needed.

Is there an interest in proposal to add this functionality? It can look like another method: `context.Detached(ctx context.Context)` that simply does not add it to the parent cancellation tree.

Sean Liao

unread,
Sep 3, 2022, 12:08:39 PM9/3/22
to golang-nuts

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/26f54d88-e475-413e-84f0-9076f5aaba28n%40googlegroups.com.

TheDiveO

unread,
Sep 4, 2022, 7:34:58 AM9/4/22
to golang-nuts
I'm wondering what the "sometimes" really is. More so as I had just this week to deal with the podman REST API client misuse of context. The still widely v3 client only carries private variables that point to the client object. It completely ignored deadlines and cancelations by using the background context for each request.

To be able to later upgrade to v4 I'm using a context mix in using github.com/thediveo/wye.

So what would be the sometimes use cases, are tunesischen due to arcane upstream API design or is there a good reason to pass value that really don't belong into a context?
Reply all
Reply to author
Forward
0 new messages