golang

Go Channels under the hood

resource: https://www.youtube.com/watch?v=KBZlN0izeiY

Take aways

  1. On a blocked buffered channel, the blocked go-routine calls gopark in the runtime scheduler of go to park itself and allow other go routines to run. The blocked value is stored in the channel in the sender queue.
  2. Go channels are synchronised using mutexes.
  3. To unblock the buffered channel, the receiver will copy the value from the sender queue to the channel’s circular queue. The receiver does this instead of the sender, which needs to wake up as the receiver has made space on the channel again because to avoid acquiring the mutex by the sender.
  4. In case of a un-buffered queue, a common stack frame is used by the two go routines. The sender goroutines writes to the exact stack frame shared with the other receiving go routine. This avoids the mutex and the receiver can directly read the value from memory.