Created
February 27, 2023 15:51
-
-
Save abtris/b67534a21e5c95ee52daf90afecb897d to your computer and use it in GitHub Desktop.
CTRL+C in main.go and context.WithCancel
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 ( | |
"context" | |
"errors" | |
"fmt" | |
"os" | |
"os/signal" | |
) | |
func operation2(ctx context.Context) error { | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("operation2 done") | |
return errors.New("operation2") | |
default: | |
fmt.Println("operation1") | |
} | |
} | |
} | |
func operation1(ctx context.Context) error { | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("operation1 done") | |
return errors.New("operation1") | |
default: | |
fmt.Println("operation1") | |
err := operation2(ctx) | |
if err != nil { | |
return errors.New("operation2") | |
} | |
} | |
} | |
} | |
func main() { | |
ctx := context.Background() | |
// trap Ctrl+C and call cancel on the context | |
ctx, cancel := context.WithCancel(ctx) | |
c := make(chan os.Signal, 1) | |
signal.Notify(c, os.Interrupt) | |
defer func() { | |
signal.Stop(c) | |
cancel() | |
}() | |
go func() { | |
select { | |
case <-c: | |
cancel() | |
case <-ctx.Done(): | |
} | |
}() | |
operation1(ctx) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment