Created
September 22, 2016 14:26
-
-
Save natdm/907455616e70c1cb43f83f28ed89a9ba to your computer and use it in GitHub Desktop.
Playing with context
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" | |
"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