Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created July 22, 2023 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostretsov/20935b56ab85593ec1ae59a1aa407470 to your computer and use it in GitHub Desktop.
Save ostretsov/20935b56ab85593ec1ae59a1aa407470 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"runtime"
)
type myCtx struct {
context.Context
}
func (d *myCtx) Done() <-chan struct{} {
c := make(chan struct{})
return c
}
func Example_routinesCustomContext() {
fmt.Println("routines before", runtime.NumGoroutine())
_, cancel := context.WithCancel(&myCtx{Context: context.Background()})
fmt.Println("routines, ctx is just created", runtime.NumGoroutine())
cancel()
runtime.GC() // updates the goroutines counter faster than sleep
fmt.Println("routines, ctx is cancelled", runtime.NumGoroutine())
// Output:
// routines before 2
// routines, ctx is just created 3
// routines, ctx is cancelled 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment