Skip to content

Instantly share code, notes, and snippets.

@filewalkwithme
Last active March 10, 2018 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save filewalkwithme/0d7f2a77dc17218d5ac81b95c316d7e3 to your computer and use it in GitHub Desktop.
Save filewalkwithme/0d7f2a77dc17218d5ac81b95c316d7e3 to your computer and use it in GitHub Desktop.
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