I'm using context.Context
to control multiple goroutines. A goroutine listens context.Done()
, then print now date string. And the process listens syscall.SIGHUP
which cancel context and then create new goroutine with context created before.
I think when syscall.SIGHUP
emitting, the process will print one date string, however got two.
This process is running on ubuntu18.04
.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
go printDate(ctx)
sg := make(chan os.Signal)
signal.Notify(sg, syscall.SIGHUP)
for {
select {
case <-sg:
cancel()
go printDate(ctx)
}
}
}
func printDate(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
}
}
I expect the output to be
2019-01-02 01:02:03
but actual output is:
2019-01-02 01:02:03
2019-01-02 01:02:03