为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 goroutine 返回多个值?

如何从 goroutine 返回多个值?

Go
哈士奇WWW 2023-02-06 19:04:02
我找到了一些带有“从 Goroutines 中获取值”的示例->链接有展示如何获取值,但如果我想从多个 goroutines 返回值,它就不会工作。那么,有人知道该怎么做吗? package mainimport (    "fmt"    "io/ioutil"    "log"    "net/http"    "sync")// WaitGroup is used to wait for the program to finish goroutines.var wg sync.WaitGroupfunc 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)<- 将出错。
查看完整描述

1 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

是的,只需多次从频道读取:

answerOne := <-nums
answerTwo := <-nums
answerThree := <-nums

Channels 的功能类似于线程安全的队列,允许您将值排队并一个一个地读出

附注:您应该在等待组中添加 3 个,或者根本不添加一个。<-nums 将阻塞,直到 nums 上的值可用,因此没有必要


查看完整回答
反对 回复 2023-02-06
  • 1 回答
  • 0 关注
  • 195 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号