使用goroutines时,在golang中打印准确的计数器



因此,我已经设置了goroutines,它们正在加速函数request中的请求。我正在尝试实现一个计数器,它可以统计发送了多少请求,但由于goroutines有点"重复"这个过程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)

}
}
}

哪个输出符合预期(每个数字1000x(:

1
1
1

您可以使用此函数以goroutine保存方式递增计数器

https://pkg.go.dev/sync/atomic@go1.17.5#AddInt32

例子是琐碎的

// count_checks := 0 
var count_checks int64 = 0
// your code here
// count_checks ++
sync.AddInt32(&count_checks, 1)

最新更新