Go学习笔记-协程

错误:

fatal error: all goroutines are asleep - deadlock!

 

goroutine 1 [chan receive]:

 

1、channel的缓冲区默认为0,直接写入会报错,错误如上

c := make(chan int) 不带缓冲区通道
c <- 1

向不带缓冲区通道写入,会等待能够接收操作,并且确保该值被成功接收。
会引起无限等待

  有配对的goroutine读取,正常执行 

c := make(chan int)
go func() {
        c <- 1
        c <- 2
        c <- 3

}()
 <-c

不带缓冲区的阻塞顺序:

c := make(chan int)
    go func() {
        c <- 1
        fmt.Println(4)
        c <- 2
        fmt.Println(5)
        c <- 3
        fmt.Println(6)

    }()
    fmt.Println(7)
    fmt.Println(<-c)
    fmt.Println(8)
    fmt.Println(<-c)
    fmt.Println(9)
    fmt.Println(<-c)
    fmt.Println(10)

输出:

7

4

1

8

2

9

5

6

3

10

 

3、for range 会一直读取channel内的值,如果没有close 会报错,报错如上

 

c := make(chan int, 1)

 

go func() {

 

     c <- 1

 

     c <- 2

 

     c <- 3

 

     //close(c)

 

 }()

 

 for i := range c {

 

     fmt.Println(i)

 

 }

 

4、select case 会执行尽快能返回的case,都不能尽快返回,会阻塞等待
case 表达式都会被执行



 

  

 

posted on 2016-08-05 15:13  Hudan  阅读(187)  评论(0)    收藏  举报

导航