如何解决Goroutine睡眠和代码死锁。怎么解决呢??
您至少需要初始化您的频道(如果频道为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)
}
}
解决方法
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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。