我是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)
}
最佳答案
主要的分类尝试在doSomething
函数中尝试多次写入通道。 read
函数仅读取一次通道。因此,写入操作将等待,直到其他方从该通道读取。由于主goroutine被阻止,这将导致死锁。
如果阻塞操作不在主goroutine中,则只要主goroutine结束,Go程序就会结束,程序将结束。如果主要功能可以结束,就不会有死锁。
关于go - 不知道为什么这会在golang中陷入僵局?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42087504/