我找到了一些带有“从 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 关注
- 195 浏览
添加回答
举报
0/150
提交
取消
