Last active
March 10, 2018 09:52
-
-
Save filewalkwithme/0d7f2a77dc17218d5ac81b95c316d7e3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"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