我是 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 := <-c
results = results + "\n" + temp
return results
}
func main(){
go reads(c)
doSomething(c)
}
最佳答案
Main gorouting 尝试多次写入 doSomething
函数中的 channel 。 read
函数只读取 channel 一次。因此写操作将等到其他方从 channel 中读取。由于主 goroutine 被阻塞,这将导致死锁。
如果阻塞操作不在 main goroutine 中,则程序将在 main goroutine 结束时随着 Go 程序结束而结束。如果 main 函数可以结束,就不会有死锁。
关于go - 不确定为什么这是 golang 中的僵局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087504/