Created
October 19, 2015 13:13
-
-
Save michaljemala/73dde464b6b78becf2d1 to your computer and use it in GitHub Desktop.
Fix for the http://www.gofragments.net/client/blog/concurrency/2015/09/22/goroutinesSyncWithWaitGroup/index.html
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/ioutil" | |
| "log" | |
| "net/http" | |
| "sync" | |
| ) | |
| func main() { | |
| urls := []string{ | |
| "http://www.reddit.com/r/programming.go", | |
| } | |
| // a channel | |
| jsonResponses := make(chan string) | |
| var wg sync.WaitGroup //def.1 | |
| wg.Add(len(urls)) //def.2 | |
| for _, url := range urls { | |
| // as many goroutines as there are urls ! | |
| // Note the way each goroutine gets a different url value, | |
| // through the use of an "anonymous closure". | |
| // The current url is passed to the closure as a parameter, | |
| // masking the url variable from the outer for-loop. | |
| // This allows each goroutine to have its own copy of url; | |
| // otherwise, the next iteration of the for-loop would update url in all | |
| // goroutines. | |
| go func(url string) { | |
| defer wg.Done() //def.3, inside each Goroutines | |
| res, err := http.Get(url) | |
| if err != nil { | |
| log.Fatal(err) | |
| } else { | |
| defer res.Body.Close() | |
| body, err := ioutil.ReadAll(res.Body) | |
| if err != nil { | |
| log.Fatal(err) | |
| } else { | |
| jsonResponses <- string(body) //send on channel | |
| } | |
| } | |
| }(url) | |
| } | |
| go func() { | |
| wg.Wait() //def.4 | |
| // finished... close the channel | |
| close(jsonResponses) | |
| }() | |
| for response := range jsonResponses { //receive on channel until we consumed everything | |
| fmt.Println(response) | |
| } | |
| } | |
| /* Expected Output: | |
| A list of .... text in json format. | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Correct. Version 3... to come... and maybe version 4...