不知道为什么这是golang的僵局?
我是新手,不知道为什么会这样?我希望不断地从doSomething读取结果,并将其存储在函数read中,而不使用for循环不知道为什么这是golang的僵局?,go,Go,我是新手,不知道为什么会这样?我希望不断地从doSomething读取结果,并将其存储在函数read中,而不使用for循环 func doSomething(c chan<- string){ // recursive function does something c <- result return dosomething(c) } func reads(c <-chan string){ results := "" temp :
func doSomething(c chan<- string){ // recursive function does something
c <- result
return dosomething(c) }
func reads(c <-chan string){
results := ""
temp := <-c
results = results + "\n" + temp
return results
}
func main(){
go reads(c)
doSomething(c)
}
主gorouting尝试在doSomething函数中多次写入通道。读取功能仅读取通道一次。因此,写入操作将等待其他方从通道读取数据。这将在主goroutine被阻止时死锁
如果阻塞操作不在主goroutine中,则只要主goroutine结束,程序就会在Go程序结束时结束。如果主函数可以结束,就不会出现死锁。您正在尝试从空通道读取,因为读取是并发执行的,而doSomething没有。有几种方法可以解决这个问题。注意,这与正确的体系结构或有效的方法无关。下面的示例解决了原始代码段的死锁问题,而不是更多 同时读写: 我更喜欢第一种和第二种方法的结合 先读后写这与正确的设计相差甚远:
有这样的例子来重现会很好,否则会很难理解这个过程。请确保您的递归有一个基本情况,并且每个递归调用都会使您更接近基本情况。如果需要的话。
package main
func doSomething(c chan<- string) { // recursive function does something
c <- "result"
doSomething(c)
}
func reads(c <-chan string) {
results := <-c
fmt.Println("Boo", results)
}
func main() {
c := make(chan string)
go reads(c)
go doSomething(c) // Write concurrentely
}
func reads(c <-chan string) {
// Use select
select {
case res := <-c:
fmt.Println("received message", res)
default:
fmt.Println("no results received")
}
}
func main() {
c := make(chan string)
go doSomething(c)
reads(c) // Read after write
}