我正在运行以下 go code并且它不产生输出:
package main
import "fmt"
//import "strconv"
import "time"
func Wait(){
time.Sleep(2000 * time.Millisecond)
}
func Print(c chan string){
fmt.Println("Running Print go-routine")
for{
fmt.Println("len(c): ", len(c))
str := <- c
fmt.Println(str)
}
}
func main() {
c := make(chan string, 4)
c <- "0"
c <- "1"
c <- "2"
c <- "3"
Wait()
fmt.Println("Before go Print(c)")
go Print(c)
fmt.Println("After go Print(c)")
}
有死锁吗? Print(c)
函数甚至没有被调用...?这对我来说很奇怪。
go playground 中的链接是:http://play.golang.org/p/tDjEJKwkRJ
最佳答案
没有错误,在 goroutine 中调用了 Print() 函数,但主程序紧随其后退出...因此 goroutine 终止。
阅读此演讲:Go Concurrency Patterns (或更好,view it's video),以了解 channel 和 goroutines 的工作原理。
请记住,当 main 函数返回时程序结束。
关于concurrency - 下面的go代码有死锁吗?不输出通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872823/