Skip to content

Instantly share code, notes, and snippets.

@quenbyako
Created August 26, 2021 11:55
Show Gist options
  • Save quenbyako/b1c9c8fd5de2eb683c8d7f1ca695f19c to your computer and use it in GitHub Desktop.
Save quenbyako/b1c9c8fd5de2eb683c8d7f1ca695f19c to your computer and use it in GitHub Desktop.
How to make context with two cancel funcs
// link to go playground: https://play.golang.org/p/_XpSn6NoNVY
package main
import (
"context"
"time"
)
func main() {
ctx1, cancel1 := context.WithCancel(context.Background())
ctx2, cancel2 := context.WithCancel(ctx1)
cancel1() // if you cancel first context, second will be cancelled too.
// cancel2() // if you cancel second one, only second context will be cancelled, first will work
_, _ = ctx1, cancel1
_, _ = ctx2, cancel2
go func() {
<-ctx1.Done()
println("ctx 1 done")
}()
go func() {
<-ctx2.Done()
println("ctx 2 done")
}()
time.Sleep(time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment