当我运行 goroutines 时,我通常得到 40 作为值,我知道它的并发性,但为什么最后一个数字来了?我想输出必须是:
Page number: 34
Page number: 12
Page number: 8
Page number: 2
Page number: 29
示例源代码:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func getWebPageContent(url string, c chan int, val int) interface{} {
if r, err := http.Get(url); err == nil {
defer r.Body.Close()
if body, err := ioutil.ReadAll(r.Body); err == nil {
c <- val
return string(body)
}
} else {
fmt.Println(err)
}
return "XoX"
}
const MAX_TH = 40
func main() {
// pln := fmt.Println
messages := make(chan int)
for j := 0; j < MAX_TH; j++ {
go func() { getWebPageContent("http://www.example.com", messages, j) }()
}
routine_count := 0
var page_number int
for {
page_number = <-messages
routine_count++
fmt.Println("Page number: ", page_number)
if routine_count == MAX_TH {
break
}
}
close(messages)
}
慕无忌1623718
慕码人8056858
相关分类