title: Go channels and deadlock
body: <p>I'm trying to understand the Go language. I tried to create two goroutines
  that chain the flow between them using two channels:</p>
  
  <pre><code>func main() {
  c1 := make(chan int)
  c2 := make(chan int)
  
  go func() {
      for i := range c1{
          println("G1 got", i)
          c2 &lt;- i
      }
  }()
  
  go func() {
      for i := range c2 {
          println("G2 got", i)
          c1 &lt;- i
      }
  }()
  
  
  c1 &lt;- 1
  
  time.Sleep(1000000000 * 50)
  }
  </code></pre>
  
  <p>As expected this code prints:</p>
  
  <pre><code> G1 got 1
   G2 got 1
   G1 got 1
   G2 got 1
   ....
  </code></pre>
  
  <p>Until the main function exits.</p>
  
  <p>But if I send another value to one of the channels from main, it suddenly blocks:</p>
  
  <pre><code>func main() {
  c1 := make(chan int)
  c2 := make(chan int)
  
  go func() {
      for i := range c1{
          println("G1 got", i)
          c2 &lt;- i
      }
  }()
  
  go func() {
      for i := range c2 {
          println("G2 got", i)
          c1 &lt;- i
      }
  }()
  
  
  c1 &lt;- 1
  
  time.Sleep(1000000000 * 1)
  
  c1 &lt;- 2
  
  time.Sleep(1000000000 * 50)
  }
  </code></pre>
  
  <p>It outputs </p>
  
  <pre><code>G1 got 1
  G2 got 1
  G1 got 1
  G2 got 1
  G1 got 2
  </code></pre>
  
  <p>and then blocks until the main ends.</p>
  
  <p>The value "2" sent to c1 arrives to the first goroutie, which sends it to c2, but the second
  goroutine never receives.</p>
  
  <p>(Using buffered channels with size 1 (either c1 or c2) works in this example)</p>
  
  <p>Why does it happen? When this happens in real code, how can I debug it?</p>