Last active
March 8, 2022 23:59
-
-
Save wcamarao/ad0b20afb798a4aa22bfddf59dddcae2 to your computer and use it in GitHub Desktop.
Golang concurrency
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" | |
"io" | |
"io/ioutil" | |
"net/http" | |
"time" | |
) | |
func main() { | |
start := time.Now() | |
channel := make(chan string) | |
sites := []struct{ name, url string }{ | |
{"Go", "http://golang.org"}, | |
{"Haskell", "http://haskell.org"}, | |
{"Python", "http://python.org"}, | |
} | |
for _, site := range sites { | |
go get(site.name, site.url, channel) | |
} | |
for i := 0; i < len(sites); i++ { | |
fmt.Print(<-channel) | |
} | |
duration := time.Since(start).Seconds() | |
fmt.Printf("Finished in %.2f seconds", duration) | |
} | |
func get(name, url string, channel chan<- string) { | |
start := time.Now() | |
res, err := http.Get(url) | |
if err != nil { | |
channel <- fmt.Sprintf("%s: %s", name, err) | |
return | |
} | |
size, _ := io.Copy(ioutil.Discard, res.Body) | |
res.Body.Close() | |
duration := time.Since(start).Seconds() | |
channel <- fmt.Sprintf("%s (%s) [%d bytes in %.2fs]\n", name, url, size, duration) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment