如何从 goroutine 返回多个值?

我找到了一些带有“从 Goroutines 中获取值”的示例->链接

有展示如何获取值,但如果我想从多个 goroutines 返回值,它就不会工作。那么,有人知道该怎么做吗?

 package main


import (

    "fmt"

    "io/ioutil"

    "log"

    "net/http"

    "sync"

)


// WaitGroup is used to wait for the program to finish goroutines.

var wg sync.WaitGroup


func responseSize(url string, nums chan int) {

    // Schedule the call to WaitGroup's Done to tell goroutine is completed.

    defer wg.Done()


    response, err := http.Get(url)

    if err != nil {

        log.Fatal(err)

    }

    defer response.Body.Close()

    body, err := ioutil.ReadAll(response.Body)

    if err != nil {

        log.Fatal(err)

    }

    // Send value to the unbuffered channel

    nums <- len(body)

}


func main() {

    nums := make(chan int) // Declare a unbuffered channel

    wg.Add(1)

    go responseSize("https://www.golangprograms.com", nums)

    go responseSize("https://gobyexample.com/worker-pools", nums)

    go responseSize("https://stackoverflow.com/questions/ask", nums)

    fmt.Println(<-nums) // Read the value from unbuffered channel

    wg.Wait()

    close(nums) // Closes the channel

    // >> loading forever

另外,这个例子,工作池

是否可以从结果中获取值:fmt.Println(<-results)<- 将出错。


哈士奇WWW
浏览 196回答 1
1回答

当年话下

是的,只需多次从频道读取:answerOne&nbsp;:=&nbsp;<-nums answerTwo&nbsp;:=&nbsp;<-nums answerThree&nbsp;:=&nbsp;<-numsChannels 的功能类似于线程安全的队列,允许您将值排队并一个一个地读出附注:您应该在等待组中添加 3 个,或者根本不添加一个。<-nums 将阻塞,直到 nums 上的值可用,因此没有必要
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go