Created
October 7, 2018 20:36
-
-
Save unanoc/5a4bc2bc118af79838609cd7f71ac018 to your computer and use it in GitHub Desktop.
Using context cancel.
This file contains hidden or 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" | |
"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