我找到了一些帶有“從 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 上的值可用,因此沒有必要
- 1 回答
- 0 關注
- 153 瀏覽
添加回答
舉報
0/150
提交
取消