【问题标题】:Print an accurate counter in golang while using goroutines使用 goroutine 时在 golang 中打印一个准确的计数器
【发布时间】: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

【问题讨论】:

    标签: go goroutine


    【解决方案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)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多