简体   繁体   中英

Golang buffered channel receive data before even sent

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM