Created
July 7, 2018 22:51
-
-
Save bojand/a2efa5844a941ede6670aa00ed880990 to your computer and use it in GitHub Desktop.
go concurrency
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" | |
"strings" | |
"time" | |
) | |
func upper(input string) string { | |
fmt.Println("upper " + input) | |
time.Sleep(time.Second) | |
return strings.ToUpper(input) | |
} | |
func main() { | |
concurrency := 5 | |
sem := make(chan bool, concurrency) | |
urls := []string{"url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url2", "url10", "url11", "url12", "url13", "url14", "url15", "url16", "url17"} | |
resCh := make(chan string, len(urls)) | |
for _, url := range urls { | |
sem <- true | |
go func(u string) { | |
defer func() { <-sem }() | |
resCh <- upper(u) | |
}(url) | |
} | |
for i := 0; i < cap(sem); i++ { | |
sem <- true | |
} | |
results := make([]string, 0, len(urls)) | |
for i := 0; i < cap(resCh); i++ { | |
r := <-resCh | |
results = append(results, r) | |
} | |
fmt.Printf("%+v", results) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment