一尘不染

Goroutine睡眠和代码死锁。怎么解决呢?

go

http://play.golang.org/p/r92-KtQEGl

我正在尝试执行此代码。它将引发死锁错误。

我想念什么?

package main

import "tour/tree"
import "fmt"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int){
    var temp chan int
    ch <- t.Value
    if t.Left!=nil{go Walk(t.Left,temp)}
    if t.Right!=nil{go Walk(t.Right,temp)}
    for i := range temp{
        ch <- i
    }
    close(ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool

阅读 218

收藏
2020-07-02

共1个答案

一尘不染

您至少需要初始化您的频道(如果频道为nil,则范围将永远被阻塞)

  var temp chan int = make(chan int)
  var ch chan int = make(chan int)

请参阅http://play.golang.org/p/Gh8MZlyd3B(仍然处于死锁状态,但至少显示结果)

此版本使用 两个 临时通道,不会死锁:http :
//play.golang.org/p/KsnmKTgZ83

package main

import "tour/tree"
import "fmt"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    var temp1 chan int = make(chan int)
    var temp2 chan int = make(chan int)
    ch <- t.Value
    if t.Left != nil {
        go Walk(t.Left, temp1)
    }
    if t.Right != nil {
        go Walk(t.Right, temp2)
    }
    if t.Left != nil {
        for i := range temp1 {
            ch <- i
        }
    }
    if t.Right != nil {
        for i := range temp2 {
            ch <- i
        }
    }
    close(ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool

func main() {
    var ch chan int = make(chan int)
    go Walk(tree.New(1), ch)
    for i := range ch {
        fmt.Println(i)
    }
}
2020-07-02