【发布时间】:2022-01-14 17:11:16
【问题描述】:
所以我设置了我的 goroutines 来加速我在函数 request 中的请求。我正在尝试实现一个计数器来计算已发送的请求数,但是由于 goroutine 有点“重复”该过程 x 次,因此很难做出准确的计数器。有没有其他方法,或者有人知道准确记录发送的请求数量的方法吗?
代码:
func routine() {
fmt.Println()
rep := 1000
results := make(chan string)
for i := 0; i < rep; i++ {
go func(num int) {
results <- request(num)
}(i)
}
for i := 0; i < rep; i++ {
fmt.Println(<-results)
}
}
...
func request(num int) string {
client := &http.Client{}
count_checks := 0
for {
req, err := http.NewRequest("GET", "https://endpoint.com/users", nil)
resp, err := client.Do(req)
if err != nil {
print(err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
if contents != nil {
count_checks++
fmt.Println(count_checks)
}
}
}
哪些输出符合预期(每个数字 1000 倍):
1
1
1
【问题讨论】: