从通道读取多个 goroutine 会给出错误的数据计数



我正在开发一个程序,我在其中读取 csv 文件并执行以下操作:

完整代码可在:这里

我的 CSV 文件可在以下位置找到:CSV 文件

问题是有时我得到 A 和 B 的正确计数,有时我得到错误的计数。

我认为我在Goroutines和渠道通信中做错了什么。

当我评论第二个goroutine时,我得到了第一个goroutine的正确结果。但是当我取消注释第二个 Goroutine,我得到的 Goroutine 1 和 2 的输出都不正确。

谁能解释一下我做错了什么?

此外,当我运行 -race main.go 时,结果向我显示了比赛条件。

func main() {
    input, err := os.Open("CSV.csv")
    if err != nil {
        fmt.Println("Error while opening CSV file.")
        return
    }
    defer input.Close()
    formattedStartDateRange,err := time.Parse(time.RFC3339, startDateRange)
    if err != nil {
        fmt.Println(err)
    }
    formattedendDateRange,err := time.Parse(time.RFC3339, endDateRange)
    if err != nil {
        fmt.Println(err)
    }
    reader := csv.NewReader(input)
    reader.FieldsPerRecord = -1
    files := make(map[string]chan []string)
    wg := &sync.WaitGroup{}
    var line []string
    for line, err = reader.Read(); err == nil; line, err = reader.Read() {
        ch, ok := files[line[0]]
        if ok {
            ch <- line
        } else {
            ch = make(chan []string, 8)
            ch <- line
            wg.Add(2) // Must wait for 2 calls to 'done' before moving on
            go func() {
                UserMapMutex.Lock()
                if (findNumberOfBuilds(formattedStartDateRange, formattedendDateRange, ch, wg)) {
                    totalBuildCount++
                }
                UserMapMutex.Unlock()
                wg.Done()
            }()
            go func() {
                UserMapMutex.Lock()
                countUserBuildFrequency(ch, wg)
                UserMapMutex.Unlock()
                wg.Done()
            }()

            files[line[0]] = ch
        }
    }

    if err.Error() != "EOF" {
        fmt.Println("Error while reading CSV file.")
        return
    }
    for _, ch := range files {
        close(ch)
    }
    wg.Wait()
    fmt.Println("Total Build executed from 1st November to 30th November =", totalBuildCount)
    fmt.Println("Total Build", userBuildFreq["5c00a8f685db9ec46dbc13d7"])
    fmt.Println("Done!")
}

在这两种情况下,您的 wg。Done() 在你启动 goroutine 后立即被调用。这意味着您的等待组不会等待 goroutine 完成。请记住,当您调用 goroutine时,调用过程会继续。尝试放置工作组。Done() 在 goroutine 调用,当它完成工作时。

go func(wg) {
    // do stuff
    wg.Done
}

go func(wg) {
    defer wg.Done
    // do stuff
}

相关内容

最新更新