添加元素后通道长度为零

Length of channel is zero after adding element

我学习了 Go 中的缓冲通道,并且对我隐藏了一些魔法。 我有这个代码

package main

import (
    "fmt"
)

func write(ch chan int) {
    for i := 1; i <= 5; i++ {
        ch <- i
        fmt.Printf("Channel's length is %d\n", len(ch))
    }
    close(ch)
}
func main() {
    ch := make(chan int, 2)
    go write(ch)

    for v := range ch {
        fmt.Println(v)
    }
}

输出是

Channel's length is 0
Channel's length is 1
Channel's length is 2
1
2
3
4
Channel's length is 2
Channel's length is 0
5

为什么write goroutine第一次迭代的channel长度为0?我不知道什么?

根据 GO 缓冲区的概念,您可以根据定义的缓冲区大小(在您的情况下为 2)将元素推送到通道中。但是当一个元素被推入通道时,主 GO 例程正在读取相同的元素,这导致通道的大小减小到零。因此,如果您在读取语句之前放置一些 time.Sleep,您将获得预期的结果。

`

package main
import (
    "fmt"
    "time"
)

func write(ch chan int) {
    for i := 1; i <= 5; i++ {
        ch <- i
        fmt.Printf("Channel's length is %d\n", len(ch))
    }
    close(ch)
}
func main() {
    ch := make(chan int, 2)
    go write(ch)
    time.Sleep(2*time.Second)
    for v := range ch {
        fmt.Println(v)
        time.Sleep(2*time.Second)
    }
}`

上面代码的输出是:

Channel's length is 1

Channel's length is 2

1

Channel's length is 2

2

Channel's length is 2

3

Channel's length is 2

4

5