Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"context"
"log"
"sync"
"time"
)
var wg sync.WaitGroup
var stopEverything = make(chan bool)
func main() {
//number of workers
n := 4
ctx, cancel := context.WithCancel(context.Background())
//from 1 to n
for i := 1; i <= n; i++ {
wg.Add(1)
go worker(ctx, i)
}
mainLoop:
for {
select {
case <-stopEverything:
log.Printf("Callin cancel()...")
cancel()
break mainLoop
}
}
wg.Wait()
}
//worker prints his ID every 2 seconds
func worker(ctx context.Context, id int) {
//internal counter used to trigger an error condition
x := 0
for {
select {
default:
x++
//ERROR CONDITION!!!
//WE SHOULD NEVER EVER EVER HAVE X GREATER THAN 3 WHEN ID=4 !!!!
//STOP EVERYTHING
if id == 4 && x > 3 {
log.Printf("goroutine #%v: WE SHOULD NEVER EVER EVER HAVE X GREATER THAN 3 WHEN ID=4 !!!! STOP EVERYTHING", id)
stopEverything <- true
}
time.Sleep(2 * time.Second)
log.Printf("goroutine #%v", id)
case <-ctx.Done():
log.Printf("RETURNING from goroutine #%v", id)
wg.Done()
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment