Last active
March 10, 2018 09:51
-
-
Save filewalkwithme/232dedb3c8f0f5836c8e6f86bbb27232 to your computer and use it in GitHub Desktop.
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" | |
"log" | |
"sync" | |
"time" | |
) | |
var wg sync.WaitGroup | |
var stopEverything = make(chan bool) | |
func main() { | |
//number of workers | |
ctx, cancel := context.WithCancel(context.Background()) | |
wg.Add(6) | |
go worker(ctx, 1) | |
go worker(ctx, 2) | |
go workerWithBug(ctx, 3) | |
go worker(ctx, 4) | |
go worker(ctx, 5) | |
go worker(ctx, 6) | |
go func() { | |
for { | |
select { | |
case <-stopEverything: | |
log.Printf("Callin cancel()...") | |
cancel() | |
return | |
} | |
} | |
}() | |
wg.Wait() | |
} | |
//worker who waits the same amount of seconds as his ID number | |
func worker(ctx context.Context, id int) { | |
longRunningTicker := time.NewTicker(time.Duration(id) * time.Second) | |
loop: | |
for { | |
select { | |
case <-longRunningTicker.C: | |
log.Printf("goroutine #%v: SUCCESS!", id) | |
break loop | |
case <-ctx.Done(): | |
log.Printf("RETURNING from goroutine #%v", id) | |
break loop | |
} | |
} | |
wg.Done() | |
} | |
//worker who waits the same amount of seconds as his ID number | |
func workerWithBug(ctx context.Context, id int) { | |
errorTicker := time.NewTicker(time.Duration(id) * time.Second) | |
loop: | |
for { | |
select { | |
case <-errorTicker.C: | |
stopEverything <- true | |
log.Printf("goroutine #%v: FAILED!", id) | |
break loop | |
case <-ctx.Done(): | |
log.Printf("RETURNING from goroutine #%v", id) | |
break loop | |
} | |
} | |
wg.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment