本博客已迁移至 www.0x520.com
之前用channel练习的时候遇到一个问题,看似好像代码合理,而且编译也不会有问题,但忘记了一个重要的channel特性。
正确的代码:
package main
import "fmt"
func foo(){
defer fmt.Println("World")
fmt.Println("Hello")
}
func sum(x,y int,c chan int){
c <- x + y
}
func main(){
foo()
c := make (chan int);
go sum(24,18,c)
fmt.Println(<-c);
}
如果我把代码改成:
package main
import "fmt"
func foo(){
defer fmt.Println("World")
fmt.Println("Hello")
}
//func sum(x,y int,c chan int){
// c <- x + y
//}
func main(){
foo()
// c := make (chan int);
// go sum(24,18,c)
// fmt.Println(<-c);
c := make (chan int)
d := 2
c <- d+3
fmt.Println(<-c)
}
或者
package main
import "fmt"
func foo(){
defer fmt.Println("World")
fmt.Println("Hello")
}
func sum(x,y int,c chan int){
c <- x + y
}
func main(){
foo()
c := make (chan int);
sum(24,18,c)
fmt.Println(<-c);
}
都会出现以下错误:
Hello
World
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/Users/john/a1.go:20 +0x60
exit status 2
这是为什么呢,看似合理的程序,是忽略了Channel是阻塞的,如果没有使用go Channel就一直在阻塞的状态,执行就死循环了。这个特性也在很多场合带来了方便。
