golang 部分理解:關於channel 和 goroutine 例子

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
部分理解:關於channel 和 goroutine 例子
package mainimport
"strconv"import "fmt"func main() { //在主goroutine中要先有讀取chan的請求,之後才可以賦值,即有需求才會有chan賦值的舉動,否則先別碰chan,不然會死結 //1 taskChan := make(chan string, 3) doneChan := make(chan int, 1) for i := 0; i < 3; i++ { taskChan <- strconv.Itoa(i) fmt.Println("send: ", i) } go func() { for i := 0; i < 3; i++ { task := <-taskChan fmt.Println("received: ", task) } doneChan <- 1 }() <-doneChan // 2和3是一對,只是把給chan的賦值或是讀值調換了 //2 ch2 := make(chan int)
//ch2 <- 1 如果在這先給ch2賦值,那麼就會阻塞,因為不知道有誰在用這個ch2. go func() {
<-ch2 fmt.Println("chan 2 received") }() ch2 <- 1 //放置在這兒剛好了 fmt.Println("over") //3 ch3 := make(chan int) go func() { ch3 <- 1 fmt.Println("chan 3 received") }() <-ch3 //這是告訴主goroutine有一個叫ch3的chan需要等待,等到ch3完成後,就可以繼續往下走了 fmt.Println("over")

//3
     //帶緩衝的chan,需要把緩衝裝滿後才能繼續後續
    c2 := make(chan int, 2)
    //寫資料位元置1  此處賦值會死結
    c2 <- 1
    c2 <- 3
    c2 <- 2
    go func() {
        fmt.Println("before 2 received")
        <-c2
        fmt.Println("after 2 received")
    }()
    //寫資料位元置2 此處是正確位置

    fmt.Println("end")

}

 最後還有個問題,goroutine中在去嵌套goroutine會怎麼樣?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.