golang for loop with buffered channel

时间:2018-01-15 22:10:59

标签: for-loop go channel buffered

我正在试验golang频道,并且遇到以下简单程序未终止的问题。

基本上我想制作一些异步HTTP获取请求,然后等待,直到它们全部完成。我使用的是缓冲频道,但我不确定这是不是惯用的方式。

func GetPrice(quotes chan string) {
    client := &http.Client{}
    req, _ := http.NewRequest("GET", "https://some/api", nil)
    req.Header.Set("Accept", "application/json")
    res, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    quotes <- string(body)
}

func main() {
    const max = 3
    quotes := make(chan string, max)
    for i := 0; i < max; i++ {
        go GetPrice(quotes)
    }

    for n := range quotes {
        fmt.Printf("\n%s", n)
    }
}

程序成功打印3(最多)项目

{"price":"1.00"}
{"price":"2.00"}
{"price":"3.00"}

然后阻止并永不退出。

3 个答案:

答案 0 :(得分:0)

我希望这会对你有所帮助。

package main

import (
   "fmt"
   "net/http"
   "io/ioutil"
)  


func GetPrice(quotes chan string, count int) {
    for count > 0 {
        client := &http.Client{}
    req, _ := http.NewRequest("GET", "https://postman-echo.com/get?foo1=bar1&foo2=bar2", nil)
    req.Header.Set("Accept", "application/json")
    res, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    quotes <- string(body)
    count--
}
close(quotes)

}


func main() {
    const max = 3
    ch := make(chan string)
    go GetPrice(ch, max)
    for num := range ch {
        fmt.Println(num)
    }
}

答案 1 :(得分:0)

您可以采取的另一种方式:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func GetPrice(quotes chan string) {
    client := &http.Client{}
    req, _ := http.NewRequest("GET", "https://some/api", nil)
    req.Header.Set("Accept", "application/json")
    res, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    quotes <- string(body)
}

func run(quotes chan string, quit chan bool, max int) {
    for num := range quotes {
        fmt.Println(num)
        max--

        if max == 0 {
            quit <- true
        }
    }
}

func main() {
    const max = 3
    quotes := make(chan string)
    quit := make(chan bool)

    go run(quotes, quit, max)

    for i := 0; i < max; i++ {
        go GetPrice(quotes)
    }

    <-quit
}

答案 2 :(得分:0)

sync.WaitGroup可以在这里等待所有goroutines然后关闭quotes频道:

func getPrice(quotes chan<- string, onExit func()) {
    go func() {
        defer onExit()
        client := &http.Client{}
        req, _ := http.NewRequest("GET", "https://some/api", nil)
        req.Header.Set("Accept", "application/json")
        res, err := client.Do(req)
        if err != nil {
            panic(err) // should be handled properly
        }
        defer res.Body.Close()
        body, err := ioutil.ReadAll(res.Body)
        quotes <- string(body)
    }()
}

func main() {
    var wg sync.WaitGroup
    const max = 3
    quotes := make(chan string, max)
    for i := 0; i < max; i++ {
        wg.Add(1)
        getPrice(quotes, func() { wg.Done() })
    }

    go func() {
        defer close(quotes)
        wg.Wait()
    }()

    for n := range quotes {
        fmt.Printf("\n%s", n)
    }
}