Answer the question
In order to leave comments, you need to log in
How to exit main after completing all routines?
I have a routine that runs 10500 other routines. main is listening to the channel. But when routines die, main doesn't die.
Answer the question
In order to leave comments, you need to log in
https://golang.org/pkg/sync/#example_WaitGroup
While channels are faster, I prefer wg control.
upd.
Control the number of routines. Break the application into small functions.
in the main, 10 routines are immediately launched for executing requests, 10 routines for analyzing the response from a third-party service, 10 routines for something else.
Routines for executing requests are received, for example, from a single channel, the URL to which the request must be made. You send the URL to the channel, the free routine suffices and executes the request, receives the answer, transfers to another channel, from which there is already enough free routine to analyze the response. Well, etc.
Here is a rough example of how I do it
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
urls := []string{"http://google.ru", "http://vk.com", "http://ya.ru"}
chanUrls := make(chan string, 100)
chanRes := make(chan http.Response, 100)
chanPrint := make(chan string, 100)
for _, url := range urls {
chanUrls <- url
}
close(chanUrls)
go httpGet(chanUrls, chanRes)
go analys(chanRes, chanPrint)
printRes(chanPrint)
}
func httpGet(chanUrls <-chan string, chanRes chan<- http.Response) {
defer close(chanRes)
for url := range chanUrls {
res, err := http.DefaultClient.Get(url)
if err == nil {
chanRes <- *res
}
}
}
func analys(chanRes <-chan http.Response, chanPrint chan<- string) {
defer close(chanPrint)
for res := range chanRes {
body, err := ioutil.ReadAll(res.Body)
if err == nil {
chanPrint <- string(body)
}
}
}
func printRes(chanPrint <-chan string) {
for pr := range chanPrint {
fmt.Println(pr)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question