Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Last active February 12, 2023 00:15
Show Gist options
  • Save hnakamur/617f5a9ae16a63cb8c65 to your computer and use it in GitHub Desktop.
Save hnakamur/617f5a9ae16a63cb8c65 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
}
@hnakamur
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment