Comment

Comment by shoo

re: "# channels < # goroutines"

  func doSomethingTwice() error {
      // Issue occurs below
      errc := make(chan error)
  
      go func() {
          defer fmt.Println("done wth a")
          errc <- doSomething("a")
      }()
      go func() {
          defer fmt.Println("done with b")
          errc <- doSomething("b")
      }()
      err := <-errc
      return err
  }
> When one routine writes to the channel, the program exits and the other goroutine is lost, building up memory use as a results

I'm not very familiar with go, but my guess would be that since the two goroutines send to an unbuffered channel that is read at most once, the "slower" of the two goroutines will sit there blocking attempting to send to a channel that will never be read. So this would "leak" a goroutine that would consume resources while the process was still running, but it doesn't have anything to do with the program exiting.

https://golang.org/ref/spec#Channel_types

https://golang.org/ref/spec#Send_statements

> How do we fix this? We simply increase the number of channels to 2

The fix is okay but the language is a bit hazy, there's still only one channel, but now it's a buffered channel with capacity to hold up to 2 messages, so the two goroutines don't need to block waiting for a receiver to be ready to synchronously receive the message they are sending.

parent shoo 8 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton