Created
July 23, 2025 11:36
-
-
Save pedrobertao/88b92af2ec03ad4c858590a3cb9a4208 to your computer and use it in GitHub Desktop.
Go routines + context.timeout
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" | |
"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