go channel learning

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   strong   for   div   

I spent several hours to figure out some conceptions about channel tonight

 

1. buffered channel and non-buffered channel

buffered channel

bufferedchan := make(chan int, 1)

when adding element into bufferedchan, it will not blocked if it is not full.

for example:

package mainimport "fmt"func main() {    messages := make(chan string, 1)    messages <- "buffered"    fmt.Println("quit!")}

the program won‘t block and the answer is:

quit!

 

2.channel is thread safe, 

package mainimport "fmt"func main() {    jobs := make(chan int, 5)    done := make(chan bool)    go func() {                           ------------------------------- (Part I)        fmt.Println("enter go routinue")        for {            j, more := <-jobs            if more {                fmt.Println("received job", j)            } else {                fmt.Println("received all jobs")                done <- true                return            }        }    }()    jobs <- 1                             ------------------------------- (part II)    jobs <- 2    jobs <- 3    close(jobs)    fmt.Println("sent all jobs and closed")
<-done ------------------------------- (Part III)}

the result is:

sent all jobs and closed
enter go routinue
received job 1
received job 2
received job 3
received all jobs

 

firstly, it executes (Part II)  and stop at  <-done.

and then a child routinue executes (Part I) and done<-true.

Now the channel done is actived and continue to execute.

 

*If the channel jobs is not closed in main, the statement "j, more := <-jobs" in (Part I) will block.  the deadlock will happen.

*If we don‘t set "<-done" in main, main will not wait the child routinue to finish.

 

go channel learning

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.