使用 select 的 Golang channel 不会停止

标签 go channel

这里是 Go-lang 新手。我正在尝试 Go 的 Go 之旅,遇到了一个关于 channel 的练习 (https://tour.golang.org/concurrency/7)。 这个想法是走两棵树,然后评估树是否等价。

我想使用等待来自两个 channel 的结果的选择来解决这个练习。当两者都完成时,我评估生成的 slice 。不幸的是,该方法进入无限循环。我添加了一些输出以查看发生了什么,并注意到只有一个 channel 被关闭,然后再次打开。

我显然做错了什么,但我看不出是什么。 我的问题是我做错了什么?关于关闭使下面的代码进入无限循环的 channel ,我做了什么假设?

package main

import (
    "golang.org/x/tour/tree"
    "fmt"
)

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    _walk(t, ch)
    close(ch)
}

func _walk(t *tree.Tree, ch chan int) {
    if (t.Left != nil) {
        _walk(t.Left, ch)
    }
    ch <- t.Value
    if (t.Right != nil) {
        _walk(t.Right, ch)
    }
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)

    var out1 []int
    var out2 []int

    var tree1open, tree2open bool
    var tree1val, tree2val int
    for {
        select {
        case tree1val, tree1open = <- ch1:
            out1 = append(out1, tree1val)
        case tree2val, tree2open = <- ch2:
            out2 = append(out2, tree2val)
        default:
            if (!tree1open && !tree2open) {
                break
            } else {
                fmt.Println("Channel open?", tree1open, tree2open)
            }
        }
    }

    if (len(out1) != len(out2)) {
        return false
    }

    for i := 0 ; i < len(out1) ; i++ {
        if (out1[i] != out2[i]) {
            return false
        }
    }

    return true
}

func main() {
    ch := make(chan int)
    go Walk(tree.New(1), ch)

    for i := range ch {
        fmt.Println(i)
    }

    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))
}

最佳答案

“break”语句终止最里面的“for”、“switch”或“select”语句的执行。
参见:http://golang.org/ref/spec#Break_statements
您示例中的 break 语句终止了 select 语句,即“最内层”语句。
所以添加label: ForLoop before for循环并添加break ForLoop

ForLoop:
    for {
        select {
        case tree1val, tree1open = <-ch1:
            if tree1open {
                out1 = append(out1, tree1val)
            } else if !tree2open {
                break ForLoop
            }
        case tree2val, tree2open = <-ch2:
            if tree2open {
                out2 = append(out2, tree2val)
            } else if !tree1open {
                break ForLoop
            }
        }
    }

如果您想自己解决该问题,请不要阅读其余部分,完成后再回来: 解决方案 1(与您的类似):

package main

import "fmt"
import "golang.org/x/tour/tree"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    _walk(t, ch)
    close(ch)
}

func _walk(t *tree.Tree, ch chan int) {
    if t.Left != nil {
        _walk(t.Left, ch)
    }
    ch <- t.Value
    if t.Right != nil {
        _walk(t.Right, ch)
    }
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    ch1, ch2 := make(chan int), make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)

    tree1open, tree2open := false, false
    tree1val, tree2val := 0, 0
    out1, out2 := make([]int, 0, 10), make([]int, 0, 10)
ForLoop:
    for {
        select {
        case tree1val, tree1open = <-ch1:
            if tree1open {
                out1 = append(out1, tree1val)
            } else if !tree2open {
                break ForLoop
            }
        case tree2val, tree2open = <-ch2:
            if tree2open {
                out2 = append(out2, tree2val)
            } else if !tree1open {
                break ForLoop
            }
        }
    }
    if len(out1) != len(out2) {
        return false
    }
    for i, v := range out1 {
        if v != out2[i] {
            return false
        }
    }
    return true
}

func main() {
    ch := make(chan int)
    go Walk(tree.New(1), ch)
    for i := range ch {
        fmt.Println(i)
    }
    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))
}

输出:

1
2
3
4
5
6
7
8
9
10
true
false    

另一种方式:

package main

import "fmt"
import "golang.org/x/tour/tree"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    _walk(t, ch)
    close(ch)
}

func _walk(t *tree.Tree, ch chan int) {
    if t != nil {
        _walk(t.Left, ch)
        ch <- t.Value
        _walk(t.Right, ch)
    }
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    ch1, ch2 := make(chan int), make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)
    for v := range ch1 {
        if v != <-ch2 {
            return false
        }
    }
    return true
}

func main() {
    ch := make(chan int)
    go Walk(tree.New(1), ch)
    for v := range ch {
        fmt.Println(v)
    }
    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))
}

输出:

1
2
3
4
5
6
7
8
9
10
true
false    

并查看:
Go Tour Exercise: Equivalent Binary Trees

关于使用 select 的 Golang channel 不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37895441/

相关文章:

go - 是否关闭 channel 阻塞直到接收者读取它

concurrency - Go 例程可以共享 channel 的所有权吗?

go - 关于主例程和子例程同时监听同一个 channel 的问题

ubuntu - 需要在 Ubuntu 14.04 (trusty64) 上将 Go 1.2.1 升级到 1.3+

sql-server - 如何在 Gorm 中获取特定日期的最大值?

dictionary - 有没有更好的方法来解析这个 map ?

string - 从 []byte 转换为字符串的开销,反之亦然

go - 第一个完成时如何安全地绕过其他 goroutine 的结果

bots - 如何将 Telegram channel 的成员转移到另一个 Telegram channel

if-statement - reader.ReadString 不会删除第一次出现的 delim