Created
August 26, 2021 11:55
-
-
Save quenbyako/b1c9c8fd5de2eb683c8d7f1ca695f19c to your computer and use it in GitHub Desktop.
How to make context with two cancel funcs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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