目錄git
咱們經常使用的是無緩衝channel :github
make(chan type)
其實make() 建立chan的第二個參數可設置緩衝channel的大小。
上述語句等價於 make(chan type, 1) 即建立了一個緩衝區大小爲1channelgolang
下面看有緩衝channel的兩個例子.this
demo :
協程1 :每隔1s 往有10個緩衝的channel裏面寫一條msg,3d
協程2:每隔3s 取一條msg,code
package main import( //"fmt" "time" "strconv" log "github.com/astaxie/beego/logs" ) func main() { log.Debug("---main--- start") msgs := make(chan string, 10) i := 0 go func() { time.Sleep(3*time.Second) for { time.Sleep(1*time.Second) i++ msg := "msg " + strconv.Itoa(i) msgs <- msg log.Debug("------ put msg : ", msg) } }() go func() { for { get := <- msgs log.Debug("---------------- pop msg : ", get) time.Sleep(3*time.Second) } }() time.Sleep(100*time.Second) }
能夠看到當緩衝區滿了之後,寫channel的操做會阻塞在那裏等待讀端取走msg後才能寫入。協程
實際場景中咱們可能不但願程序阻塞,那麼能夠使用select來控制,當緩衝區滿了後忽略該條msg繼續執行咱們的程序。blog
package main import( //"fmt" "time" "strconv" log "github.com/astaxie/beego/logs" ) func main() { log.Debug("---main--- start") msgs := make(chan string, 3) i := 0 go func() { time.Sleep(3*time.Second) for { time.Sleep(1*time.Second) i++ msg := "msg " + strconv.Itoa(i) select { case msgs <- msg: log.Debug("------ put msg : ", msg) default : log.Debug("-----msgs chan cache full sleep 1s-----") log.Debug("-----ignore this msg-----> : ", msg) } } }() go func() { for { get := <- msgs log.Debug("---------------- pop msg : ", get) time.Sleep(3*time.Second) } }() time.Sleep(100*time.Second) }
能夠看到,由於寫端寫入過快,再寫入msg6時緩衝區已滿,執行default丟棄了msg6,讀端在取走msg5後, 取走的不是msg6,而是msg7get