第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 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 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號