title: golang 2 go routines if one terminates terminate the other one
body: <p>so I am using gorillas websocket library and I'm building a websocket server when I receive a connection I create 2 go routines one to read incoming messages from the client and another 1 to listen for in coming messages sent to the channel and then send them to the client.</p>
  
  <pre><code>func (p *Player) EventLoop() {
      l4g.Info("Starting player %s event loop", p)
      go p.readFromSocket()
      go p.writeToSocket()
  
      //blocks until we receive an interrupt from the read channel
      &lt;-p.closeEventChan
      p.cleanup() //nothing else to do so lets cleanup
  }
  
  func (p *Player) writeToSocket() {
      for m := range p.writeChan {
          if p.conn == nil {
              break
          }
  
          if reflect.DeepEqual(network.Packet{}, m) == true {
              break
          }
  
          if err := p.conn.WriteJSON(m); err != nil {
              break
          }
      }
      p.closeEventChan &lt;- true
  }
  
  func (p *Player) readFromSocket() {
      for {
          if p.conn == nil {
              break
          }
  
          m := network.Packet{}
  
          if err := p.conn.ReadJSON(m); err != nil {
              break
          }
      }
      p.closeEventChan &lt;- true
  }
  
  func (p *Player) Cleanup() {
  
      //make sure the channels get a close message which will break us out of the go routines
      close(p.writeChan)
      close(p.closeEventChan)
  
      //only close the connection if we have a connection
      if p.conn != nil {
          p.conn.Close()
          p.conn = nil
      }
  }
  </code></pre>
  
  <p>my problem is if we leave the <code>readFromSocket()</code> loop <code>Cleanup()</code> is called however we never leave the <code>writeToSocket()</code> loop ! this problem can be simpler demonstrated in this go playground  <a href="https://play.golang.org/p/49bh7bbbG-" rel="nofollow">https://play.golang.org/p/49bh7bbbG-</a></p>
  
  <p>how can we fix this so if we leave the <code>writeToSocket()</code> loop we also leave the <code>readFromSocket()</code> loop and vice vesa? </p>
  
  <p>I was under the impression that this would work as if you call close on a channel (<code>close(p.writeChan)</code>) the default value that the channel accepts will be sent</p>