How Unbuffered channel work

119 views
Skip to first unread message

Manjeet S

unread,
Jun 5, 2022, 10:06:53 AM6/5/22
to golang-nuts
I just started to learn Go Language, and I'm enjoying writing code in Go.
So today, I'm trying to understand how the unbuffered channel works

Can someone help me to understand why this code is not working. I'm expecting that <-ch wait until we receive from channel ch


func main() {
    ch := make(chan struct{})
    ch2 := make(chan int)
   
    go func() {
        arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        for _, v := range arr {
            ch2 <- v
        }
    }()

    go func() {
        for t := range ch2 {
            fmt.Println(t)
        }
        ch <- struct{}{}
    }()

    <-ch
}

Thanks & Regards  

Manjeet Thakur

pere...@gmail.com

unread,
Jun 5, 2022, 10:18:37 AM6/5/22
to golang-nuts
You did not close ch2 in the first goroutine. Therefore, the second goroutine never reaches line "ch <- struct{}{}"

Aleksei Perevozov
воскресенье, 5 июня 2022 г. в 16:06:53 UTC+2, manjee...@gmail.com:

Jan Mercl

unread,
Jun 5, 2022, 10:19:40 AM6/5/22
to Manjeet S, golang-nuts
On Sun, Jun 5, 2022 at 4:06 PM Manjeet S <manjee...@gmail.com> wrote:

> Can someone help me to understand why this code is not working. I'm expecting that <-ch wait until we receive from channel ch

The range statement at line 18 does not complete unless the channel is
closed. Adding `close(ch2)` at line 14 fixes the problem:
https://go.dev/play/p/OnmJD04VYDA

Manjeet S

unread,
Jun 5, 2022, 12:19:10 PM6/5/22
to golang-nuts
Thank you so much  Aleksei Perevozov and Jan Mercl 
Reply all
Reply to author
Forward
0 new messages