Skip to content

Instantly share code, notes, and snippets.

@natdm
Created September 22, 2016 14:26
Show Gist options
  • Save natdm/907455616e70c1cb43f83f28ed89a9ba to your computer and use it in GitHub Desktop.
Save natdm/907455616e70c1cb43f83f28ed89a9ba to your computer and use it in GitHub Desktop.
Playing with context
package main
import (
"fmt"
"time"
"golang.org/x/net/context"
)
func main() {
someHandler()
}
func someHandler() {
ctx, cancel := context.WithCancel(context.Background())
for i := 0; i < 5; i++ {
go doStuff(ctx, i)
}
time.Sleep(time.Second * 6)
cancel()
time.Sleep(time.Second * time.Duration(2))
}
func doStuff(ctx context.Context, num int) {
for {
select {
case <-ctx.Done():
fmt.Println("Done working")
return
default:
fmt.Println("go", num, "working")
}
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment