Skip to content

Instantly share code, notes, and snippets.

@rcosnita
Created March 8, 2024 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcosnita/199e71e0cda18326882ae7cc5caed852 to your computer and use it in GitHub Desktop.
Save rcosnita/199e71e0cda18326882ae7cc5caed852 to your computer and use it in GitHub Desktop.
Golang sequencing with context cancellation
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