Last active
June 3, 2025 17:11
-
-
Save kmesiab/a25614247c743546ab97a54b5392640e to your computer and use it in GitHub Desktop.
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/v2" | |
| "time" | |
| ) | |
| type Thing struct{} | |
| func main() { | |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) | |
| defer cancel() | |
| c := make(chan Thing) | |
| for i := 0; i < 5; i++ { | |
| go worker(c, ctx) | |
| } | |
| for i := 0; i < 10; i++ { | |
| // simulate work going on | |
| // in a non blocked main thread | |
| fmt.Println("doing work on main") | |
| } | |
| // holds the thing returned by some worker into the channel, one at a time | |
| var o Thing | |
| // this is blocking | |
| for { | |
| select { | |
| case o = <-c: | |
| fmt.Printf("A worker did stuff with %v\n", o) | |
| // build in an activity timeout | |
| case <-time.After(2 * time.Second): | |
| fmt.Println("No activity for 2 seconds, exiting") | |
| return | |
| } | |
| } | |
| } | |
| func worker(c chan Thing, ctx context.Context) { | |
| fmt.Println("A worker started") | |
| indeterminateWorkCount := rand.IntN(25) | |
| for i := 0; i < indeterminateWorkCount; i++ { | |
| // honor the context cancelation | |
| select { | |
| case <-ctx.Done(): | |
| return | |
| default: | |
| } | |
| // do the normal worker stuff | |
| time.Sleep(1) | |
| c <- Thing{} | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment