On Sat, Sep 4, 2021 at 5:55 PM Michael Dwyer <michael.k.dw...@gmail.com>
wrote:

> I encountered a deadlock when reading from a buffered channel.
> The deadlock occurs when an attempt is made to read from the channel
> twice, without an intermediate write to the channel.
>

That is not a deadlock. Reading from a buffered channel blocks when the
channel is empty. From https://golang.org/ref/spec#Channel_types:


Otherwise, the channel is buffered and communication succeeds without
blocking if the buffer is not full (sends) or not empty (receives). A
nil channel
is never ready for communication.
You can use the "select" operator (
https://golang.org/ref/spec#Select_statements) to detect if the channel is
empty.


> The problematic code is as follows:
>
> func main() {
> myInt      := 432
>
> readerChan := make(chan int, 3)
>
> for forI := 0; forI <= 10000; forI++ {
> readerChan <- myInt
> fmt.Printf("%d:", <- readerChan)
> fmt.Printf("%d:", <- readerChan)
> }
>
> close(readerChan)
> }
>
> The first read from variable readerChan succeeds.
> The second read from variable readerChan results in a deadlock.
>
> I have two links to playground.
> The first link is the problematic code.
> The second link is for similar code that has an intervening write to the
> channel.
>
> I understand that a buffered channel allows a queue of results to be
> stored from other Go routines writing to the channel.
> But, the code is attempting multiple read operations.
>
> Looking for a technical explanation to help me better understand this
> particular case.
> Thanks in advance ...
>
>
> The problematic playground link : https://play.golang.org/p/veo7phAZzMv
> The working playground link     : https://play.golang.org/p/qvYZNN9keqN
>
>
> THANX(MKD).
>
> --
> 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+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/44057a7a-b0aa-4ea1-9fb3-39836cd5713dn%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/44057a7a-b0aa-4ea1-9fb3-39836cd5713dn%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>


-- 
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CABx2%3DD_H-na_90DyY_PCzakLjBuz3ehN1hoVOj1Y%2BTc26tPN_A%40mail.gmail.com.

Reply via email to