Created
February 8, 2023 08:26
-
-
Save xvzf/f229069feff5e00783892eacd362baf4 to your computer and use it in GitHub Desktop.
Go context timeout example
This file contains 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" | |
"sync" | |
"time" | |
) | |
func fiz(ctx context.Context) { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("fiz: context canceled") | |
case <-time.After(1 * time.Second): | |
fmt.Println("fiz: after 1 sec") | |
} | |
} | |
func buz(ctx context.Context) { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("buz: context canceled") | |
case <-time.After(10 * time.Second): | |
fmt.Println("buz: after 10s ") | |
} | |
} | |
func main() { | |
var wg sync.WaitGroup | |
// Create a context that is both manually cancellable and time out after 5 sec | |
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
defer cancel() | |
// fiz and buz are called in parallel | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
fiz(ctx) | |
}() | |
// buz and buz are called in parallel | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
buz(ctx) | |
}() | |
// Blocking until all goroutines are done | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment