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

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装