Skip to content

Instantly share code, notes, and snippets.

@liubin
Forked from hnakamur/main.go
Created April 18, 2018 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liubin/b26acb79f9a3e704132a5b6c8c1cb356 to your computer and use it in GitHub Desktop.
Save liubin/b26acb79f9a3e704132a5b6c8c1cb356 to your computer and use it in GitHub Desktop.
A go example to stop a worker goroutine when Ctrl-C is pressed (MIT License)
package main
import (
"fmt"
"os"
"os/signal"
"time"
"golang.org/x/net/context"
)
func main() {
c1, cancel := context.WithCancel(context.Background())
exitCh := make(chan struct{})
go func(ctx context.Context) {
for {
fmt.Println("In loop. Press ^C to stop.")
// Do something useful in a real usecase.
// Here we just sleep for this example.
time.Sleep(time.Second)
select {
case <-ctx.Done():
fmt.Println("received done, exiting in 500 milliseconds")
time.Sleep(500 * time.Millisecond)
exitCh <- struct{}{}
return
default:
}
}
}(c1)
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt)
go func() {
select {
case <-signalCh:
cancel()
return
}
}()
<-exitCh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment