Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 为什么在全局范围内声明通道会产生死锁问题_Go_Concurrency_Scope_Deadlock_Channel - Fatal编程技术网

Go 为什么在全局范围内声明通道会产生死锁问题

Go 为什么在全局范围内声明通道会产生死锁问题,go,concurrency,scope,deadlock,channel,Go,Concurrency,Scope,Deadlock,Channel,在3个代码段中,其中一个在本地范围内声明了通道,另一个代码段会出现死锁问题,前面的一个代码段说,尽量避免在全局范围内声明通道。我查了一下,但没有找到任何解释 尽管我没有阻止通道发送和接收,但为什么全局作用域通道出现错误?为什么我会遇到僵局问题 除了范围和初始化之外,makechan int与var myChan int有何不同 有人能解释并建议更好的文章/文档/链接/PDF,以便有效地使用通道并在Go中实现并发性吗 为简洁起见,代码段中省略了导入和“package main” // 1. cha

在3个代码段中,其中一个在本地范围内声明了通道,另一个代码段会出现死锁问题,前面的一个代码段说,尽量避免在全局范围内声明通道。我查了一下,但没有找到任何解释

尽管我没有阻止通道发送和接收,但为什么全局作用域通道出现错误?为什么我会遇到僵局问题

除了范围和初始化之外,makechan int与var myChan int有何不同

有人能解释并建议更好的文章/文档/链接/PDF,以便有效地使用通道并在Go中实现并发性吗

为简洁起见,代码段中省略了导入和“package main”

// 1. channel declared in global scope
var c chan int
func main(){
    go send()
    fmt.Println(<-c)
}
func send(){
    c <- 42
}
//output: fatal error: all goroutines are asleep - deadlock!

// 2. channel declared in global scope + sending channel to goroutine
var c chan int
func main(){
    go send(c)
    fmt.Println(<-c)
}
func send(c chan int){
    c <- 42
}
//output: fatal error: all goroutines are asleep - deadlock!

// 3. using channel as local scope and sharing it with goroutine
func main(){
    c := make(chan int)
    go send(c)
    fmt.Println(<-c)
}
func send(c chan int){
    c <- 42
}

因为通过声明一个未初始化的var c chan int,c有它的类型的零值,在chan的情况下是nil

如果确实需要,则错误消息会显示此信息。两个goroutine都以nil chan发送/接收:

使用make,您将显式初始化变量c,该变量不是nil

这与全局范围本身无关。事实上,如果正确初始化变量,例如var c chan int=makechan int,即使在全局范围内,程序也不会死锁

其他阅读资料:

如果信道为零,则发送方和接收方彼此没有参考;它们都被封锁在独立的频道上等待,永远不会解除封锁


因为通过声明一个未初始化的var c chan int,c有它的类型的零值,在chan的情况下是nil

如果确实需要,则错误消息会显示此信息。两个goroutine都以nil chan发送/接收:

使用make,您将显式初始化变量c,该变量不是nil

这与全局范围本身无关。事实上,如果正确初始化变量,例如var c chan int=makechan int,即使在全局范围内,程序也不会死锁

其他阅读资料:

如果信道为零,则发送方和接收方彼此没有参考;它们都被封锁在独立的频道上等待,永远不会解除封锁

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive (nil chan)]:
main.main()
    /tmp/sandbox288806111/prog.go:11 +0x5c

goroutine 18 [chan send (nil chan)]:
main.send()
    /tmp/sandbox288806111/prog.go:15 +0x39
created by main.main
    /tmp/sandbox288806111/prog.go:10 +0x39