Alex

More on Channels (Video 26)

func get(url string, ch chan<- result) { }
func collect(ch <-chan result) map[string]int { }

Closed Channels

Nil Channels

Reproduced from https://www.youtube.com/watch?v=fCkxKGd6CVQ

Rendezvous Model

Reproduced from https://www.youtube.com/watch?v=fCkxKGd6CVQ

Buffering

Important Note

type T struct {
  i byte
  b bool
}

func send(i int, ch chan<- *T) {
  t := &T{i: byte(i)}
  ch<- t
  t.b = true // NEVER DO THIS
}

func main() {
  vs := make([]T, 5)
  ch := make(chan *T)
  for i := range vs {
    go send(i, ch)
  }

  time.Sleep(1*time.Second)

  // This quick copy will read and copy the values written into the channel by
  // the 5 running goroutines. But there is a race condition so the value of t.b
  // for all the values is false since it is likely (but not guaranteed) that this
  // read and copy will finish before the t.b is updated in the goroutine. If the
  // channel was buffered, it would be likely (but again not a guarantee) that 
  // the value is true for all. The time.Sleep() will almost guarantee that this
  // is the case but again this is a race condition so it should never be relied upon
  for i := range vs {
    vs[i] = *<-ch
  }

  for _,v :+ range vs {
    fmt.Println(v)
  }
}

Why Buffering