Created
March 8, 2024 05:05
-
-
Save rcosnita/199e71e0cda18326882ae7cc5caed852 to your computer and use it in GitHub Desktop.
Golang sequencing with context cancellation
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" | |
"fmt" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
type SequenceChannel = chan bool | |
func loadNegID(ctx context.Context, seq SequenceChannel) { | |
select { | |
case <-ctx.Done(): | |
{ | |
seq <- true | |
return | |
} | |
default: | |
{ | |
fmt.Println("loading NegID") | |
time.Sleep(2 * time.Second) | |
fmt.Println("NegID loaded") | |
seq <- true | |
} | |
} | |
} | |
func continueProcess(ctx context.Context) bool { | |
select { | |
case <-ctx.Done(): | |
{ | |
return false | |
} | |
default: | |
{ | |
fmt.Println("second routine executed") | |
return true | |
} | |
} | |
} | |
func main() { | |
ctx, cancel := context.WithCancel(context.Background()) | |
defer cancel() | |
seqChan := make(SequenceChannel, 1) | |
seqDone := make(SequenceChannel, 1) | |
sigs := make(chan os.Signal, 1) | |
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) | |
go func() { | |
for { | |
received := <-sigs | |
if received == syscall.SIGINT { | |
fmt.Println("SIGINT received ...") | |
cancel() | |
return | |
} | |
} | |
}() | |
go func() { | |
loadNegID(ctx, seqChan) | |
}() | |
go func() { | |
select { | |
case <-seqChan: | |
{ | |
for { | |
if !continueProcess(ctx) { | |
seqDone <- true | |
return | |
} | |
time.Sleep(1 * time.Second) | |
} | |
} | |
case <-ctx.Done(): | |
{ | |
fmt.Println("context cancelled") | |
seqDone <- true | |
return | |
} | |
} | |
}() | |
<-seqDone | |
fmt.Println("Sequencing is complete") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment