Skip to content

Commit

Permalink
Use context to synchronize termination
Browse files Browse the repository at this point in the history
  • Loading branch information
adzil committed Oct 1, 2019
1 parent d1d3dac commit fb442af
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package main

import (
"context"
"flag"
"fmt"
"io"
Expand Down Expand Up @@ -222,7 +223,7 @@ func main() {
getConcat(shards))
baseArgs := buildBaseArgs(opt)
serverDir := filepath.Dir(serverPath)
done := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
var waiter sync.WaitGroup
var exitCode atomic.Value
stdins := make(map[string]io.Writer, len(shards))
Expand All @@ -236,13 +237,13 @@ func main() {
var err error
if stdins[shard], err = cmd.StdinPipe(); err != nil {
errorf("cannot pipe stdin for shard \"%s\": %s", shard, err.Error())
asyncClose(done)
cancel()
exitCode.Store(1)
break
}
if err := cmd.Start(); err != nil {
errorf("cannot start shard \"%s\": %s\n", shard, err.Error())
asyncClose(done)
cancel()
exitCode.Store(1)
break
}
Expand All @@ -258,13 +259,14 @@ func main() {
exitCode.Store(1)
}
}
if asyncClose(done) {
if err := ctx.Err(); err == nil {
cancel()
fmt.Printf("shard \"%s\" unexpectedly terminated, starting graceful termination\n", shard)
}
waiter.Done()
}(shard)
go func() {
<-done
<-ctx.Done()
Interrupt(cmd)
}()
}
Expand Down Expand Up @@ -311,8 +313,8 @@ func main() {
select {
case <-trap:
fmt.Printf("terminate request, starting graceful termination\n")
asyncClose(done)
case <-done:
cancel()
case <-ctx.Done():
}
go func() {
waiter.Wait()
Expand Down

0 comments on commit fb442af

Please sign in to comment.