Skip to content

Instantly share code, notes, and snippets.

@deividaspetraitis
Created January 19, 2018 09:08
Show Gist options
  • Save deividaspetraitis/cd0f4a8d5291c967de89a91ca32da6d8 to your computer and use it in GitHub Desktop.
Save deividaspetraitis/cd0f4a8d5291c967de89a91ca32da6d8 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
"runtime"
"context"
)
func main() {
// ctx
ctx, cancel := context.WithTimeout(context.Background(), time.Hour)
// This function returns error
go Perform(ctx)
// ...
time.Sleep(time.Second * 5)
cancel()
fmt.Println("Ctx canceled")
// runtime.Goexit makes to crash program in case
// there is no running routines
time.Sleep(time.Hour)
// too bad :(
runtime.Goexit()
}
// Following function is often found in many examples
// It returns ctx.Err() but for what reason since there is no
// way to catch it in such manner
func Perform(ctx context.Context) error {
for {
SomeFunction(ctx)
select {
case <-ctx.Done():
fmt.Println("ctx is canceled, return error")
return ctx.Err()
case <-time.After(time.Second): // sleep 1 sec
fmt.Println("ctx is not canceled, continue immediately")
}
}
return nil
}
func SomeFunction(ctx context.Context) {
fmt.Println("ping")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment