Skip to content

Instantly share code, notes, and snippets.

@unanoc
Created October 7, 2018 20:36
Show Gist options
  • Save unanoc/5a4bc2bc118af79838609cd7f71ac018 to your computer and use it in GitHub Desktop.
Save unanoc/5a4bc2bc118af79838609cd7f71ac018 to your computer and use it in GitHub Desktop.
Using context cancel.
package main
import (
"context"
"fmt"
"math/rand"
"time"
)
func worker(ctx context.Context, workerID int, result chan<- int) {
waitTime := time.Duration(rand.Intn(100)+10) * time.Millisecond
fmt.Printf("Worker %d sleeps %dms\n", workerID, waitTime/600000)
select {
case <-ctx.Done():
return
case <-time.After(waitTime):
fmt.Printf("Worker %d is done\n", workerID)
result <- workerID
}
}
func main() {
result := make(chan int, 1)
ctx, finish := context.WithCancel(context.Background())
for i := 0; i <= 10; i++ {
go worker(ctx, i, result)
}
foundValue := <-result
fmt.Printf("Found %d\n", foundValue)
finish()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment