Skip to content

Instantly share code, notes, and snippets.

@ronaldpetty
Created October 29, 2021 07:41
Show Gist options
  • Save ronaldpetty/324e0db0d059adadfccdd22b49cda906 to your computer and use it in GitHub Desktop.
Save ronaldpetty/324e0db0d059adadfccdd22b49cda906 to your computer and use it in GitHub Desktop.
try cancel
package main
import (
"context"
"time"
)
func one(ctx context.Context) {
print("one create\n")
ctx5, _ := context.WithTimeout(ctx, time.Second*5)
go two(ctx5)
select {
case <-ctx.Done():
print("one is done\n")
time.Sleep(time.Second * 3)
}
c <- "one"
}
func two(ctx context.Context) {
print("two create\n")
ctx2, _ := context.WithTimeout(ctx, time.Second*2)
go three(ctx2)
select {
case <-ctx.Done():
print("two is done\n")
time.Sleep(time.Second * 2)
}
c <- "two"
}
func three(ctx context.Context) {
print("three create\n")
select {
case <-ctx.Done():
print("three is done\n")
time.Sleep(time.Second)
}
c <- "three"
}
var c = make(chan string, 3)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
print("in main\n")
go one(ctx)
time.Sleep(time.Second)
cancel()
<-c
<-c
<-c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment