Skip to content

Instantly share code, notes, and snippets.

@niels-s
Created September 15, 2016 12:07
Show Gist options
  • Save niels-s/4bb23258366c9578bb6455ef98918bc2 to your computer and use it in GitHub Desktop.
Save niels-s/4bb23258366c9578bb6455ef98918bc2 to your computer and use it in GitHub Desktop.
Demonstrate use of defer in golang with kill sig
package main
import (
"log"
"os"
"os/signal"
"sync"
"time"
)
func main() {
defer func() {
log.Println("[DEFER] we got the defer here!!!")
}()
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Kill, os.Interrupt)
go func() {
<-signals
log.Println("[signals] We're in here!")
os.Exit(0)
}()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
log.Printf("Start sleep")
for i := 0; i < 10; i++ {
log.Printf("[SLEEP] %v seconds", i)
time.Sleep(1 * time.Second)
}
wg.Done()
}()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment