Last active
August 29, 2015 14:04
-
-
Save khaledsaikat/1fd62412b2a71601adaa to your computer and use it in GitHub Desktop.
An example of concurrency in Go programming
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" | |
"net/http" | |
) | |
var urls = []string{ | |
"http://google.com", | |
"http://yahoo.com", | |
"http://bing.com", | |
"http://youtube.com", | |
} | |
func main() { | |
start := time.Now() | |
c := make(chan string) | |
for _, url := range urls { | |
go fetch(url, c) | |
} | |
for i := 0; i < len(urls); i++ { | |
fmt.Println(<-c) | |
} | |
fmt.Println("Total Time: ", time.Since(start)) | |
} | |
func fetch(url string, c chan string) { | |
start := time.Now() | |
resp, err := http.Get(url) | |
if err != nil { | |
c <- fmt.Sprintf("Error: %s", err) | |
return | |
} | |
c <- fmt.Sprintf( "Url: %s, Time: %s, Status: %s", url, time.Since(start), resp.Status ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment