Simplify signals example

The signals example is overly complex, involving an unneeded go routine and an additional signal. This creates indirection making the code hard to understand.

The proposed change simplifies the code by removing the go routine and the additional signal, leaving the fundamental concept.
This commit is contained in:
Sébastien Besnier 2021-11-28 20:00:36 +01:00 committed by GitHub
parent c93e7c1cf8
commit 37caa048e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -18,29 +18,21 @@ func main() {
// Go signal notification works by sending `os.Signal` // Go signal notification works by sending `os.Signal`
// values on a channel. We'll create a channel to // values on a channel. We'll create a channel to
// receive these notifications (we'll also make one to // receive these notifications.
// notify us when the program can exit). // **Note** that this channel is "buffered".
sigs := make(chan os.Signal, 1) sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
// `signal.Notify` registers the given channel to // `signal.Notify` registers the given channel to
// receive notifications of the specified signals. // receive notifications of the specified signals.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// This goroutine executes a blocking receive for fmt.Println("awaiting signal")
// signals. When it gets one it'll print it out
// and then notify the program that it can finish. // Because the `sigs` channel is buffered, the program
go func() { // will wait here until it gets the expected signal and
// then exit.
sig := <-sigs sig := <-sigs
fmt.Println() fmt.Println()
fmt.Println(sig) fmt.Println(sig)
done <- true
}()
// The program will wait here until it gets the
// expected signal (as indicated by the goroutine
// above sending a value on `done`) and then exit.
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting") fmt.Println("exiting")
} }