Created
November 16, 2015 13:10
-
-
Save fortytw2/c6c04f62f74151c84523 to your computer and use it in GitHub Desktop.
Encapsulated, gracefull goroutine shutdown in
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 ( | |
"log" | |
"os" | |
"os/signal" | |
"sync" | |
"syscall" | |
"time" | |
) | |
func main() { | |
var wg sync.WaitGroup | |
work := make(chan bool) | |
go func() { | |
for { | |
work <- true | |
time.Sleep(20 * time.Millisecond) | |
} | |
}() | |
wg.Add(1) | |
go func() { | |
grace, kill := make(chan os.Signal, 1), make(chan os.Signal, 1) | |
signal.Notify(grace, syscall.SIGINT) | |
signal.Notify(kill, syscall.SIGTERM) | |
for { | |
select { | |
case _ = <-work: | |
log.Println("just doing some work, don't mind me") | |
time.Sleep(500 * time.Millisecond) | |
case _ = <-grace: | |
log.Println("Looks like I got a SIGINT, gonna clean up first") | |
wg.Done() | |
return | |
case _ = <-kill: | |
log.Println("Looks like I got a SIGTERM") | |
wg.Done() | |
return | |
} | |
} | |
}() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not
defer wg.Done()
?