码迷,mamicode.com
首页 > 其他好文 > 详细

go channel learning

时间:2014-09-19 01:08:44      阅读:256      评论:0      收藏:0      [点我收藏+]

标签: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 main

import "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 main

import "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

标签:style   blog   color   io   os   ar   strong   for   div   

原文地址:http://www.cnblogs.com/harrysun/p/3980477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!