Skip to content

Instantly share code, notes, and snippets.

@pedrobertao
Created July 23, 2025 11:36
Show Gist options
  • Save pedrobertao/88b92af2ec03ad4c858590a3cb9a4208 to your computer and use it in GitHub Desktop.
Save pedrobertao/88b92af2ec03ad4c858590a3cb9a4208 to your computer and use it in GitHub Desktop.
Go routines + context.timeout
package main
import (
"context"
"fmt"
"os"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
jobs := make(chan string)
go func() {
fmt.Println("Sleeping... 6 seconds")
time.Sleep(6 * time.Second)
jobs <- "Long routine"
}()
go func() {
fmt.Println("Sleeping... 4 seconds")
time.Sleep(4 * time.Second)
jobs <- "Short routine"
}()
for {
select {
case <-ctx.Done():
fmt.Println("Context timeout before long routine")
os.Exit(0)
case res := <-jobs:
// handle val
fmt.Println("Result: ", res)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment