channel

1.what‘s chanel?spa

  信道是什麼?簡單說,是goroutine之間互相通信的東西。相似咱們Unix上的管道(能夠在進程間傳遞消息), 用來goroutine之間發消息和接收消息。其實,就是在作goroutine之間的內存共。線程

 

2.hot to use?code

  example: blog

package main

import (
	"fmt"
	"time"
)

func main() {

	a := make(chan int)
	go func(){
		for i:=0; i<= 5; i++{
			a<-i
			time.Sleep(time.Second * 1)
		}
		close(a)
	}()
	go func(){
		for {
			select {
			case x, ok := <- a :
				if ok{
					fmt.Println(x)
					time.Sleep(time.Second * 2)
				}else{
					fmt.Println("over")
					return
				}

			}
		}
	}()

	time.Sleep(time.Second * 15)

}

  

3.trouble shouting進程

  1fatal error: all goroutines are asleep - deadlock!內存

package main

import (
    "fmt"
    "time"
)

func main() {

    a := make(chan int)
    //go func(){
        for i:=0; i<= 5; i++{
            a<-i
            time.Sleep(time.Second * 1)
        }
        close(a)
    //}()
    go func(){
        for {
            select {
            case x, ok := <- a :
                if ok{
                    fmt.Println(x)
                    time.Sleep(time.Second * 2)
                }else{
                    fmt.Println("over")
                    return
                }

            }
        }
    }()

    time.Sleep(time.Second * 15)

}

  a 爲非緩衝的channel,在main方法的主線程中輸入第一個數據的時候,channe阻塞,直接掛起。致使程序沒法進行下去。而後報錯。class

  正確的使用channel是有發有收。import

相關文章
相關標籤/搜索