doushenyu8228 2018-08-09 14:05
浏览 57
已采纳

Golang缓冲通道在发送之前就已接收数据

I am very new to golang. I get very confused when testing how channel works in Golang today.

According to the tutorial:

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

My test program looks like this:

package main

import "fmt"

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

    go func(ch chan int) int {
        for i := 0; i < 10; i++ {
            fmt.Println("goroutine: GET ", <-ch)
        }
        return 1
    }(ch)

    for j := 0; j < 10; j++ {
        ch <- j
        fmt.Println("PUT into channel", j)
    }
}

I get the output like this:

PUT into channel 0
PUT into channel 1
goroutine: GET  0
goroutine: GET  1
goroutine: GET  2
PUT into channel 2
PUT into channel 3
PUT into channel 4
PUT into channel 5
goroutine: GET  3
goroutine: GET  4
goroutine: GET  5
goroutine: GET  6
PUT into channel 6
PUT into channel 7
PUT into channel 8
PUT into channel 9

Notice that number 2 is fetched from the channel before even been put in the channel. why does this happen?

  • 写回答

1条回答 默认 最新

  • dongming6201 2018-08-09 16:09
    关注

    It doesn't. Your Println("PUT into channel") happens after you put it on the channel, meaning there's an opportunity for it to be read from the channel before that print statement is executed.

    The actual order of execution in your sample output is something along the lines of:

    1. Writer routine writes 2 to the channel.
    2. Reader routine receives 2 from the channel.
    3. Reader routine prints goroutine: GET 2.
    4. Writer routine prints PUT into channel 2

    Your reads and writes from/to the channel are happening in the expected order, it's just your print statements that make it appear to be out of order.

    If you changed the writer's order of operations to:

        fmt.Println("PUT into channel", j)
        ch <- j
    

    You would likely see output closer to what you're expecting. It still wouldn't necessarily exactly represent the order of operations, however, because:

    1. Execution is concurrent, but writes to stdout are synchronous
    2. Every function call and channel send/receive is an opportunity for the scheduler to switch, so even running with GOMAXPROCS=1, it could switch goroutines between the print and the channel operation (in the reader or the writer).

    TL;DR: don't read too much into the order of log messages when logging concurrent operations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀