在这个函数中,你可以看到我使用了 go 关键字。package mainimport ( "fmt" "math")func main() { c := make(chan string) go findGreatestDivisor(4, c) for i := 0; i <= 1; i++ { fmt.Println(<-c) }}func findGreatestDivisor(num float64, c chan string) { var counter float64 = 10000 for i := 9999; i > 0; i-- { if math.Mod(num, counter) == 0 { fmt.Println("Check..", math.Mod(4, 1)) c <- fmt.Sprintf("%f is divisble by %d", num, i) } counter-- }}有用。它给了我最大的整数。但是现在我很好奇并删除了我在此处调用该函数的 go 关键字go findGreatestDivisor(4,c)当我只是做findGreatestDivisor(4,c)它给了我错误fatal error: all goroutines are asleep - deadlock!goroutine 1 [chan send]: main.findGreatestDivisor(0x4010000000000000,0xc82001a0c0) /home/ubuntu/workspace/test.go:21 +0x37c main.main() /home/ubuntu/workspace/test.go:10 +0x61 exit status 2这是为什么?
1 回答

梦里花落0921
TA贡献1772条经验 获得超6个赞
send 语句在通道上发送一个值。通道表达式必须是通道类型,通道方向必须允许发送操作,并且要发送的值的类型必须可分配给通道的元素类型。
SendStmt = Channel "<-" Expression .
Channel = Expression .
通道和值表达式都在通信开始之前进行评估。通信阻塞,直到发送可以继续。如果接收器准备好,则可以继续在无缓冲通道上发送。如果缓冲区中有空间,则可以继续在缓冲通道上发送。关闭通道上的发送会导致运行时恐慌。在 nil 通道上发送永远阻塞。
ch <- 3 // send value 3 to channel ch
在 findGreatestDivisor
c := make(chan string)
findGreatestDivisor(4,c)
您尝试在未缓冲的频道上发送 c
c <- fmt.Sprintf("%f is divisble by %d", num, i)
但是通信会阻塞,直到发送可以继续。如果接收器准备好,则可以继续在无缓冲通道上发送。没有准备好接收器。
频道接收 c
fmt.Println(<-c)
直到您从findGreatestDivisor. 那太晚了。
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报
0/150
提交
取消