Created
March 1, 2016 02:17
-
-
Save y-abe/547f0e281b180af6ae4b to your computer and use it in GitHub Desktop.
This file contains 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 leafFunc(ctx context.Context) string { | |
ch := make(chan string) | |
go func() { | |
time.Sleep(time.Second * 2) // 2秒でhelloが返る | |
ch <- "hello" | |
}() | |
select { | |
case <-ctx.Done(): // 途中でキャンセルできる | |
return "done" | |
case resp := <-ch: | |
return resp | |
} | |
} | |
func main() { | |
ctx, cancel := context.WithCancel(context.Background()) | |
cancel() | |
resp := leafFunc(ctx) | |
fmt.Println(resp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment