0

I am reading Learning Go book and in chapter 10 the author suggests a way to avoid the deadlock with the use of select statement.

package main

import (
    "fmt"
)

func main() {
    ch1 := make(chan int)
    ch2 := make(chan int)
    go func() {
        v := 1
        ch1 <- v
        v2 := <-ch2
        fmt.Println(v, v2)
    }()
    v := 2
    var v2 int
    select {
    case ch2 <- v:
    case v2 = <-ch1:
    }
    fmt.Println(v, v2)
}

The output that I get always in Go playground is 2 1. This output is coming from main goroutine. Why don't I see anything from the anonymous function?

Is every case in select getting executed?

Also could someone please explain in greater detail the execution flow? Thanks in advance.

Ihor M.
  • 2,314
  • 2
  • 41
  • 59
  • 1
    From [this answer](https://stackoverflow.com/a/52357443/4676641), no not every `case` is getting executed. "A `select` statement without a default `case` is blocking until a read or write in **at least one of the case statements can be executed.**" (emphasis added). The linked post may not answer your question completely though so posting as a comment. – tentative May 21 '22 at 18:24

0 Answers0