Skip to content

Instantly share code, notes, and snippets.

@gerep
Forked from hnakamur/main.go
Created Nov 24, 2017
Embed
What would you like to do?
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