Created
April 11, 2017 15:14
-
-
Save johnmccabe/5de154af42f9301c64734665cd2b9371 to your computer and use it in GitHub Desktop.
Using context to handle timeouts
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 ( | |
"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