GO 例程中缓冲通道范围的输出中断

Broken output from a buffered channel range in a GO routine

为什么像下面这样的 GO 例程在使用缓冲通道时以随机顺序输出字节序列?

这里是复制错误行为的代码,其中 data.csv 是一个简单的 CSV 文件,包含 1000 行随机数据(每行大约 100 个字节)加上 header 行(其中 1001 行总计)。

package main

import (
    "bufio"
    "os"
    "time"
)

func main() {

    var channelLength = 10000
    var channel = make(chan []byte, channelLength)

    go func() {
        for c := range channel {
            println(string(c))
        }
    }()

    file, _ := os.Open("./data.csv")
    scanner := bufio.NewScanner(file)

    for scanner.Scan() {
        channel <- scanner.Bytes()
    }

    <-time.After(time.Second * time.Duration(3600))

}

这里是输出的前 6 行,作为我对 "broken output" 的意思的示例:

979,C
tharine,Vero,cveror6@blinklist.com,Female,133.153.12.53
980,Mauriz
a,Ilett,milettr7@theguardian.com,Female,226.123.252.118
981
Sher,De Laci,sdelacir8@nps.gov,Female,137.207.30.217
[...]

另一方面,如果 channelLength = 0,代码运行平稳,因此使用无缓冲通道(前 6 行,同样):

id,first_name,last_name,email,gender,ip_address
1,Hebert,Edgecumbe,hedgecumbe0@apple.com,Male,108.84.217.38
2,Minor,Lakes,mlakes1@marriott.com,Male,231.185.189.39
3,Faye,Spurdens,fspurdens2@oakley.com,Female,80.173.161.81
4,Kris,Proppers,kproppers3@gmpg.org,Male,10.80.182.51
5,Bronnie,Branchet,bbranchet4@squarespace.com,Male,118.117.0.5
[...]

数据是随机生成的。

来自 buffer.Scanner 文档:

The underlying array may point to data that will be overwritten by a subsequent call to Scan

您在使用通过通道传递的切片时存在数据竞争。您需要复制您发送的数据。在此示例中,最容易通过使用 string 而不是 []byte 并调用 scanner.Text

来实现