title: A case of `all goroutines are asleep - deadlock!` I can't figure out why
body: <p><strong><em>TL;DR:</em> A typical case of <code>all goroutines are asleep, deadlock!</code> but can't figure it out</strong></p>
  
  <p>I'm parsing the Wiktionary XML dump to build a DB of words. I defer the parsing of each article's text to a goroutine hoping that it will speed up the process.<br>
  It's 7GB and is processed in under 2 minutes in my machine when doing it serially, but if I can take advantage of all cores, why not.  </p>
  
  <p>I'm new to threading in general, I'm getting a <code>all goroutines are asleep, deadlock!</code> error.<br>
  What's wrong here?  </p>
  
  <p>This may not be performant at all, as it uses an unbuffered channel, so all goroutines effectively end up executing serially, but my idea is to learn and understand threading and to benchmark how long it takes with different alternatives:  </p>
  
  <ul>
  <li>unbuffered channel</li>
  <li>different sized buffered channel</li>
  <li>only calling as many goroutines at a time as there are <code>runtime.NumCPU()</code></li>
  </ul>
  
  <p>The summary of my code in pseudocode:  </p>
  
  <pre><code>while tag := xml.getNextTag() {
      wg.Add(1)
      go parseTagText(chan, wg, tag.text)
  
      // consume a channel message if available
      select {
      case msg := &lt;-chan:
          // do something with msg            
      default:
      }
  }
  // reading tags finished, wait for running goroutines, consume what's left on the channel
  for msg := range chan {
      // do something with msg
  }
  // Sometimes this point is never reached, I get a deadlock
  wg.Wait()
  
  ----
  
  func parseTagText(chan, wg, tag.text) {
      defer wg.Done()
      // parse tag.text
      chan &lt;- whatever // just inform that the text has been parsed
  }
  </code></pre>
  
  <p>Complete code:<br>
  <a href="https://play.golang.org/p/0t2EqptJBXE" rel="nofollow noreferrer">https://play.golang.org/p/0t2EqptJBXE</a></p>