Skip to content

Instantly share code, notes, and snippets.

@kmesiab
Last active June 3, 2025 17:11
Show Gist options
  • Select an option

  • Save kmesiab/a25614247c743546ab97a54b5392640e to your computer and use it in GitHub Desktop.

Select an option

Save kmesiab/a25614247c743546ab97a54b5392640e to your computer and use it in GitHub Desktop.
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