Basic question on Channels

129 views
Skip to first unread message

Aravindhan K

unread,
Jul 27, 2022, 3:13:34 AM7/27/22
to golang-nuts
Hi All,
When I was explaining basics of channels to newcomers, I was using the below example
 
I was expecting both Write 5 and Write 3 to be printed. But only Write 5 was printed. I couldn't reason out the behaviour, can somebody point out what I am assuming wrong about.

Thanks,
Aravindhan K

Brian Candler

unread,
Jul 27, 2022, 3:30:53 AM7/27/22
to golang-nuts
Unless a channel is buffered, it is synchronous.  A send cannot take place until the reader is ready to receive.

You can make it buffered using
    numCh = make(chan int, 1)
    go write()
    go read()

Or you can have two calls to read():

    numCh = make(chan int)
    go write()
    go read()
    go read()

Brian Candler

unread,
Jul 27, 2022, 3:35:30 AM7/27/22
to golang-nuts
BTW, using time.Sleep() to keep goroutines running is poor practice.

What I suggest is using a sync.WaitGroup.  Call wg.Add(1) for each goroutine you start; call wg.Done() when each goroutine ends; and call wg.Wait() to wait for them.

Aravindhan K

unread,
Jul 27, 2022, 5:43:01 AM7/27/22
to Brian Candler, golang-nuts
Thanks Brian, Got it.
"A send cannot take place until the reader is ready to receive." . So an unbuffered channel does not have the same behaviour as a buffered channel of size 1, fair.

I understand part about the waitGroup, I copy pasted code used to tutor the newcomers to programming itself.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2e036151-0069-44d9-9de2-3dcf98b33dban%40googlegroups.com.

Brian Candler

unread,
Jul 27, 2022, 6:16:02 AM7/27/22
to golang-nuts
I see. There's a concrete benefit in using the waitgroup though: it would have shown you the second write blocking.

Aravindhan K

unread,
Jul 27, 2022, 6:24:47 AM7/27/22
to Brian Candler, golang-nuts
Reply all
Reply to author
Forward
0 new messages