Created
February 28, 2022 12:55
-
-
Save vyskocilm/3fd3cb1a3dacd90d8cf1ca4aa204baf3 to your computer and use it in GitHub Desktop.
Double signal.NotifyContext
This file contains hidden or 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
package main | |
import ( | |
"context" | |
"log" | |
"os" | |
"os/signal" | |
"sync" | |
"time" | |
) | |
type namedContext struct { | |
ame string | |
ctx context.Context | |
} | |
func waitAll(ctxs []namedContext) chan struct{} { | |
var wg sync.WaitGroup | |
ret := make(chan struct{}) | |
for _, n := range ctxs { | |
wg.Add(1) | |
n := n | |
go func() { | |
defer wg.Done() | |
<-n.ctx.Done() | |
log.Printf("%s.Done()", n.ame) | |
}() | |
} | |
go func() { | |
wg.Wait() | |
close(ret) | |
}() | |
return ret | |
} | |
func main() { | |
ctx1, cancel1 := signal.NotifyContext(context.Background(), os.Interrupt) | |
defer func() { | |
log.Printf("cancel1()") | |
cancel1() | |
}() | |
ctx2, cancel2 := signal.NotifyContext(ctx1, os.Interrupt) | |
defer func() { | |
log.Printf("cancel2()") | |
cancel2() | |
}() | |
go func() { | |
log.Printf("INFO: waiting before killing myself") | |
time.Sleep(2 * time.Second) | |
me, err := os.FindProcess(os.Getpid()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("INFO: kill %d", os.Getpid()) | |
me.Signal(os.Interrupt) | |
}() | |
ctxs := []namedContext{ | |
{"ctx1", ctx1}, | |
{"ctx2", ctx2}, | |
} | |
select { | |
case <-context.TODO().Done(): | |
log.Printf("context.TODO().Done()") | |
case <-waitAll(ctxs): | |
log.Printf("ctx1.Done(), ctx2.Done()") | |
} | |
log.Println("fini") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output when running:
BTW: you can't run this in Go playground 🤷