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
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