猿问

当我不使用 go 关键字时,函数不起作用

在这个函数中,你可以看到我使用了 go 关键字。


package main


import (

    "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

这是为什么?


红糖糍粑
浏览 134回答 1
1回答

梦里花落0921

send 语句在通道上发送一个值。通道表达式必须是通道类型,通道方向必须允许发送操作,并且要发送的值的类型必须可分配给通道的元素类型。SendStmt = Channel "<-" Expression .Channel&nbsp; = Expression .通道和值表达式都在通信开始之前进行评估。通信阻塞,直到发送可以继续。如果接收器准备好,则可以继续在无缓冲通道上发送。如果缓冲区中有空间,则可以继续在缓冲通道上发送。关闭通道上的发送会导致运行时恐慌。在 nil 通道上发送永远阻塞。ch <- 3&nbsp; // send value 3 to channel ch在 findGreatestDivisorc := make(chan string)findGreatestDivisor(4,c)您尝试在未缓冲的频道上发送 cc <- fmt.Sprintf("%f is divisble by %d", num, i)但是通信会阻塞,直到发送可以继续。如果接收器准备好,则可以继续在无缓冲通道上发送。没有准备好接收器。频道接收 cfmt.Println(<-c)直到您从findGreatestDivisor. 那太晚了。
随时随地看视频慕课网APP

相关分类

Go
我要回答