Last active
May 26, 2017 19:04
-
-
Save marcellodesales/288cacd43426a2e1cd20 to your computer and use it in GitHub Desktop.
Refactoring of Go Channels http://talks.golang.org/2012/concurrency/support/google2.2.go to simulate concurrent downloads
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" | |
"math/rand" | |
"time" | |
) | |
type Result string | |
type Download func() Result | |
func FanInDownloads(files []string) (results []Result) { | |
c := make(chan Result) | |
for i := 0; i < len(files); i++ { | |
fileName := files[i] | |
go func() { c <- nexusDownload(fileName)() }() | |
} | |
timeout := time.After(11000 * time.Millisecond) | |
for i := 0; i < len(files); i++ { | |
select { | |
case result := <-c: | |
fmt.Println("FINISHED: " + result) | |
results = append(results, result) | |
case <-timeout: | |
fmt.Println("timed out") | |
return | |
} | |
} | |
return | |
} | |
func nexusDownload(artifactId string) Download { | |
return func() Result { | |
duration := rand.Intn(10000) | |
fmt.Println(fmt.Sprintf("Will start downloading %s... It might take %d", artifactId, duration)) | |
time.Sleep(time.Duration(duration) * time.Millisecond) | |
return Result(fmt.Sprintf("%s downloaded in %d", artifactId, duration)) | |
} | |
} | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
start := time.Now() | |
files := []string{"file1", "file2", "file3"} | |
results := FanInDownloads(files) | |
elapsed := time.Since(start) | |
fmt.Println(results) | |
fmt.Println(elapsed) | |
} |
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
mdesales@ubuntu [11/30/201423:36:56] ~/dev/github-intuit/docker-images/platform/mule-3.4/source (master *) $ go run trying.go | |
Will start downloading file1... It might take 3787 | |
Will start downloading file2... It might take 8639 | |
Will start downloading file3... It might take 5633 | |
FINISHED: file1 downloaded in 3787 | |
FINISHED: file3 downloaded in 5633 | |
FINISHED: file2 downloaded in 8639 | |
[file1 downloaded in 3787 file3 downloaded in 5633 file2 downloaded in 8639] | |
8.641097774s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment