Skip to content

Instantly share code, notes, and snippets.

@pedrobertao
Created January 14, 2021 18:01
Show Gist options
  • Save pedrobertao/d7b23cf3485704dfa1985966e82fbda4 to your computer and use it in GitHub Desktop.
Save pedrobertao/d7b23cf3485704dfa1985966e82fbda4 to your computer and use it in GitHub Desktop.
/*
How to use context with timeout to cancel a slow operation.
The same concept can be used with context.WithDeadline()
*/
package main
import (
"context"
"fmt"
"time"
)
func slowOp() {
fmt.Println("** Slow op with timeout **")
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
done := make(chan bool)
// Do something that will take more time than the timeout
go func() {
for i := 0; i < 1000000000000000; i++ {
}
done <- true
}()
select {
case <-ctx.Done():
if ctx.Err() != nil {
// Handle timeout error
fmt.Printf("Timeout context: %v\n", ctx.Err())
}
case <-done:
// Never reached...
}
}
func fastOp() {
fmt.Println("** Fast op with timeout **")
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
done := make(chan bool)
// Do something that will take some time but less than the timeout
go func() {
for i := 0; i < 5; i++ {
}
done <- true
}()
select {
case <-ctx.Done():
if ctx.Err() != nil {
// Never reached...
}
case d := <-done:
// Handle done operation
fmt.Printf("Operation done: %t \n", d)
}
}
func main() {
fastOp()
slowOp()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment