Last active
May 7, 2017 11:05
-
-
Save sundy-li/d41657cd89ba747c0c86c12bb2a85c04 to your computer and use it in GitHub Desktop.
golang-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 gomarker | |
type service func() result | |
func invokeService(ctx content.Content, s service) chan result { | |
c := make(chan result) | |
go func() { | |
c1 := make(chan result) | |
go func() { | |
c1 <- s() | |
}() | |
select { | |
case v := <-c1: | |
c <- v | |
case <-ctx.Done(): | |
// cancel this in-flight request by closing its connection. | |
} | |
}() | |
return c | |
} | |
func handleRequestByDAM() { | |
ctx, cf := context.WithCancel(context.Background()) | |
c1, c2, c3 := invokeService(ctx, service1), invokeService(ctx, service2), | |
invokeService(ctx, service3) | |
timeout := time.After(200 * time.Millisecond) | |
for { | |
select { | |
case r := <-c1: | |
//handle result1 | |
case r := <-c2: | |
//handle result2 | |
case r := <-c3: | |
//handle result3 | |
case <-timeout: | |
cf() // cancel all service invoke requests | |
return | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment