Channel Buffer Empty

https://go.dev/play/p/FMyu-rQsQGl

package main

import (
    "fmt"
    "time"
)

// G1 - goroutine
func G1(ch chan<- int) {
    for _, v := range []int{1, 2, 3, 4} {
        ch <- v
    }
    close(ch)
}

// G2 - goroutine
func G2(ch <-chan int) {
    for v := range ch {
        fmt.Println(v)
    }
}

func main() {
    ch := make(chan int, 3)

    go G1(ch)
    go G2(ch)

    time.Sleep(1 * time.Second)
    fmt.Println("done..")
}
  • When goroutine call receive on empty buffer. Goroutine is blocked, it is parked into recvq.
  • elem field of the sudog structure holds the reference to the stack variable of receiver goroutine. Image Image
  • When sender comes along, Sender finds the goroutine in recvq. Image Image
  • Sender copies the data, into the stack variable, on the receiver goroutine directly. Image
  • Pops the goroutine in recvq, and puts it into runnable state. Image Image Image Image Image
© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""