What is channel buffer size?

前端 未结 3 1747
[愿得一人]
[愿得一人] 2020-12-02 08:17

I\'m trying to create an asynchronous channel and I\'ve been looking at http://golang.org/ref/spec#Making_slices_maps_and_channels.

c := make(chan int, 10)          


        
3条回答
  •  春和景丽
    2020-12-02 09:03

    The following code illustrates the blocking of unbuffered channel:

    // to see the diff, change 0 to 1
    c := make(chan struct{}, 0)
    go func() {
        time.Sleep(2 * time.Second)
        <-c
    }()
    start := time.Now()
    c <- struct{}{} // block, if channel size is 0
    elapsed := time.Since(start)
    fmt.Printf("Elapsed: %v\n", elapsed)
    

    You may play with the code here.

提交回复
热议问题