Skip to content

Instantly share code, notes, and snippets.

@gerep
Forked from filewalkwithme/cancel2.go
Created November 24, 2017 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerep/3f27ec41617e8e365b073754acd2c3b1 to your computer and use it in GitHub Desktop.
Save gerep/3f27ec41617e8e365b073754acd2c3b1 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