duanduan8439 2016-06-06 01:01
浏览 30
已采纳

Golang实现生成器/带通道产量:奇数通道行为

The following code implements the yield pattern in golang. As an experiment I was implementing an all permutations generator. However, when I return the slice A to channel, if I do not create a new copy of the array I get an incorrect result.

Please see the code around "???". Can someone explain what happens under the covers here? I thought that since the channel is not buffered, I was guaranteed that after publishing the array's slice to the channel I was ensured that the result would be consumed before continuing.

package main

import (
    "fmt"
)

func swap(A []int, i int, j int) {
    t := A[i]
    A[i] = A[j]
    A[j] = t
}

func recurse(A []int, c chan []int, depth int) {

    if depth == len(A) {
        // ??? Why do I need to copy the data?
        // If I do c <- A I get an incorrect answer.
        ra := make([]int, len(A))
        copy(ra, A)
        c <- ra
        return
    }

    for i := depth; i < len(A); i++ {
        swap(A, depth, i)
        recurse(A, c, depth+1)
        swap(A, depth, i)
    }
}

func yieldPermutations(A []int, c chan []int) {
    recurse(A, c, 0)
    close(c)
}

func main() {
    A := []int{1, 2, 3}
    c2 := make(chan []int)

    go yieldPermutations(A, c2)
    for v := range c2 {
        fmt.Println(v)
    }
}

If I do not copy the data, I get the following result:

[1 3 2]
[1 3 2]
[2 3 1]
[2 3 1]
[3 1 2]
[3 1 2]

Obviously, the correct result (which we get with data copy) is:

[1 2 3]
[1 3 2]
[2 1 3]
[2 3 1]
[3 2 1]
[3 1 2]
  • 写回答

1条回答 默认 最新

  • douji9734 2016-06-06 02:56
    关注

    It's a mistake to think this code is like generators/yield in Python, and that's what's causing your error.

    In Python, when you request the next item from a generator, the generator starts executing and stops when the next yield <value> statement is reached. There is no parallelism in Python's generators: the consumer runs until it wants a value, then the generator runs until it produces a value, then the consumer gets the value and continues execution.

    In your go code, the goroutine executes concurrently with the code that's consuming items. As soon as an item is read from the channel from the main code, the goroutine works concurrently to produce the next. The goroutine and the consumer both run until they reach the channel send/receive, then the value is sent from the goroutine to the consumer, then they both continue execution.

    That means the backing array of A gets modified concurrently as the goroutine works to generate the next item. And that's a race condition which causes your unexpected output. To demonstrate that this is a race, insert time.Sleep(time.Second) after the channel send. Then the code produces the correct results (albeit slowly): https://play.golang.org/p/uEa_k6Brcc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值