title: When does a channel block a goroutine
body: <p>If I define a channel without buffer and write one data into it, does it block immediately(so that the kernel will look for another unblocked goroutine that reads from the channel), or does it continues execution and blocks when the next time some code tries to write into the channel again, when it hasn't been read yet?</p>
  
  <p>Below are two pieces of codes I wrote to research on this problem.</p>
  
  <p>code1:</p>
  
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import "fmt"
  
  func main() {
      c := make(chan int)
      go func() {
          for i := 0;i &lt; 3; i++ {
              c &lt;- i
              fmt.Printf("number %v inserted into channel\n", i)
          }
      }()
      for i := 0; i &lt; 3; i++ {
          fmt.Printf("number poped from channel %v\n", &lt;-c)
      }
  }
  </code></pre>
  
  <p>The output is like this:</p>
  
  <pre><code>number 0 inserted into channel
  number poped from channel 0
  number poped from channel 1
  number 1 inserted into channel
  number 2 inserted into channel
  number poped from channel 2
  </code></pre>
  
  <p>After the first time c is written into, this goroutine seems to continue to be executed, since "number 0 inserted into channel" was printed.</p>
  
  <p>code2:</p>
  
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import "fmt"
  
  func main() {
      c := make(chan int)
      c &lt;- 2
      fmt.Println("Something is written into channel")
      &lt;-c
  }
  </code></pre>
  
  <p>This piece of code cannot run correctly since a deadlock error is reported at runtime.</p>
  
  <pre><code>fatal error: all goroutines are asleep - deadlock!
  </code></pre>
  
  <p>From my view, when c &lt;-2 is executed, the goroutine is blocked(if it's not blocked, the fmt.Println line will be executed and continuing executing will unlock c at &lt;-c). When this goroutine is blocked, the kernel searches other goroutines and find none, so it reports a deadlock error.</p>
  
  <p>In summary, in the first piece of code I conclude that writting to a channel doesn't block the goroutine immediately but from the second piece of code it does. Where did I get it wrong and when does a channel blocks a goroutine?</p>