Skip to content

Instantly share code, notes, and snippets.

@filewalkwithme
Last active March 10, 2018 09:51
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/232dedb3c8f0f5836c8e6f86bbb27232 to your computer and use it in GitHub Desktop.
Save filewalkwithme/232dedb3c8f0f5836c8e6f86bbb27232 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
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