Last active
February 12, 2023 00:15
-
-
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)
This file contains 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 ( | |
"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
Go by Example: Non-Blocking Channel Operations