V
V
Vladimir Grabko2016-06-11 19:18:18
go
Vladimir Grabko, 2016-06-11 19:18:18

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

3 answer(s)
I
Ilya, 2016-06-11
@VGrabko

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)
  }
}

C
cijiw, 2016-06-11
@cijiw

You need to either close the channel or write something into it.

A
Anatoly, 2016-06-11
@taliban

Not everyone died, which means that he does not wait for the routine at all, he waits for the channels, if the lane does not come out, then not all the routines reported the end to the channel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question