Skip to content

Instantly share code, notes, and snippets.

@johnmccabe
Created April 11, 2017 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmccabe/5de154af42f9301c64734665cd2b9371 to your computer and use it in GitHub Desktop.
Save johnmccabe/5de154af42f9301c64734665cd2b9371 to your computer and use it in GitHub Desktop.
Using context to handle timeouts
package main
import (
"fmt"
"sync"
"time"
"golang.org/x/net/context"
)
var (
wg sync.WaitGroup
)
func work(ctx context.Context) error {
defer wg.Done()
for i := 0; i < 1000; i++ {
select {
case <-time.After(2 * time.Second):
fmt.Println("Doing some work ", i)
// we received the signal of cancelation in this channel
case <-ctx.Done():
fmt.Println("Cancel the context ", i)
return ctx.Err()
}
}
return nil
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
fmt.Println("Hey, I'm going to do some work")
wg.Add(1)
go work(ctx)
wg.Wait()
fmt.Println("Finished. I'm going home")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment