加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang注意Channel的阻塞特性

发布时间:2020-12-16 18:56:10 所属栏目:大数据 来源:网络整理
导读:#本博客已迁移至 [www.0x520.com][1] [1]:http://www.0x520.com 之前用channel练习的时候遇到一个问题,看似好像代码合理,而且编译也不会有问题,但忘记了一个重要的channel特性。 正确的代码: package mainimport "fmt"func foo(){ defer fmt.Println("Wor

#本博客已迁移至 [www.0x520.com][1] [1]:http://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,c chan int){
//    c <- x + y
//}

func main(){
    foo()
//    c := make (chan int);
//    go sum(24,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,c chan int){
    c <- x + y
}

func main(){
    foo()
    c := make (chan int);
    sum(24,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就一直在阻塞的状态,执行就死循环了。这个特性也在很多场合带来了方便。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读