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

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何從 goroutine 返回多個(gè)值?

如何從 goroutine 返回多個(gè)值?

Go
哈士奇WWW 2023-02-06 19:04:02
我找到了一些帶有“從 Goroutines 中獲取值”的示例->鏈接有展示如何獲取值,但如果我想從多個(gè) goroutines 返回值,它就不會(huì)工作。那么,有人知道該怎么做嗎? 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另外,這個(gè)例子,工作池是否可以從結(jié)果中獲取值:fmt.Println(<-results)<- 將出錯(cuò)。
查看完整描述

1 回答

?
當(dāng)年話下

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊

是的,只需多次從頻道讀?。?/p>

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

Channels 的功能類似于線程安全的隊(duì)列,允許您將值排隊(duì)并一個(gè)一個(gè)地讀出

附注:您應(yīng)該在等待組中添加 3 個(gè),或者根本不添加一個(gè)。<-nums 將阻塞,直到 nums 上的值可用,因此沒有必要


查看完整回答
反對 回復(fù) 2023-02-06
  • 1 回答
  • 0 關(guān)注
  • 168 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)