goroutine只通过通道传递一半的值

goroutine只通过通道传递一半的值,go,Go,我有一个文件: package main import "fmt" func combinations(result chan []byte, len int, min byte, max byte) { res := make([]byte,len) for i := 0; i < len; i++ { res[i] = min } result <- res for true { i := 0

我有一个文件:

package main
import "fmt"

func
combinations(result chan []byte, len int, min byte, max byte) {
    res := make([]byte,len)
    for i := 0; i < len; i++ {
        res[i] = min
    }
    result <- res
    for true {
        i := 0
        for i = 0; i < len; i++ {
            if res[i] < max {
                res[i] = res[i] + 1;
                break
            } else {
                res[i] = 32
            }
        }
        result <- res
        if(i == len) {
            close(result)
            return;
        }
    }
}

func
main() {
    combination_chan := make(chan []byte)
    go combinations(combination_chan, 2, 0, 5)
    for next_combination := range combination_chan {
        fmt.Printf("%x\n",next_combination)
    }
}
但是,它似乎会跳过其他每个值,并将相同的值打印两次,即:

0100
0100
0300
0300
...

它为什么要这样做?我在'result之前插入了prints,如果我们稍微简化一下,Go中的一个切片基本上是指向数组的指针,因此通过将您仍然拥有并修改的切片通过通道传递,您创建了一个数据竞争

无法判断切片的内容是否在它被传递到通道的那一刻和它被另一个goroutine从通道读取的那一刻之间被修改

因此,整个算法会导致未定义的行为,因为在修改内容时,只会一遍又一遍地传递相同的内容

在您的情况下,解决方案是在通过通道发送之前复制切片:

buf := make([]byte, len(res))
copy(buf, res)
result <- buf
buf:=make([]字节,len(res))
副本(buf,res)
结果
buf := make([]byte, len(res))
copy(buf, res)
result <- buf