Golang channel 使用總結(二)

有緩衝channel的關閉

dead lock

如果 在同一個Goroutine內,發送數大於緩衝數,就跟無緩衝類似了。

package main

import "fmt"

func main() {
    pipline := make(chan string, 1)
    pipline <- "hello world"
    pipline <- "hello Golang"
    close(pipline)

    for i := 0; i < 5; i++ {
    	fmt.Printf("%d-%s,x\n", i, <-pipline)
    }
}

運行結果

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
        /search/odin/gaozhenan/git/demo/g.go:8 +0x81
exit status 2

close後再接收到是什麼呢?

package main

import "fmt"

func main() {
    pipline := make(chan string, 1)
    go func() {
        pipline <- "hello world"
        pipline <- "hello Golang"
        close(pipline)
    }()

    for i := 0; i < 5; i++ {
    	fmt.Printf("%d-%s,x\n", i, <-pipline)
    }
}

運行結果

[@hbhly_56_128 demo]$ vi g.go     
[@hbhly_56_128 demo]$ go run g.go 
0-hello world,x
1-hello Golang,x
2-,x
3-,x
4-,x
[@hbhly_56_128 demo]$ 

如果是 chan int 呢?

package main

import "fmt"

func main() {
    pipline := make(chan int, 1)
    go func() {
        pipline <- 1
        pipline <- 2
        close(pipline)
    }()

    for i := 0; i < 5; i++ {
    	fmt.Printf("%d-%d,x\n", i, <-pipline)
    }
}

運行結果

0-1,x
1-2,x
2-0,x
3-0,x
4-0,x
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章