Golang频道不会收到消息

I try to explore go channel, i create channel buffer max 10, with gomaxprocess is 2, but i wonder why this code won't receive message

runtime.GOMAXPROCS(2)
messages := make(chan int, 9)

go func() {
    for {
        i := <-messages
        fmt.Println("Receive data:", i)
    }
}()
for i := 0; i <= 9; i++ {
    fmt.Println("Send data ", i)
    messages <- i
}

Your case works like this, though it may appear to work certain times, but it's not guaranteed to always.

Just to add some context, in an unbuffered channel, the sending go routine is blocked as it tries to send a value and a receive is guaranteed to occur before the sending go routine is awakened (in this case the main), so it may seem like a viable option in such cases. But the sending go routine may still exit before the print statement in the receiving go routine is executed. So basically you need to use a synchronization mechanism such that the sending go routine exits only after the work in the receiver is completed.

Here's how you can use a synchronization mechanism, have annotated it so that you can make better sense out of it. This will work for both buffered and unbuffered channels. Another option is to have the receive in the main thread itself so that it doesn't exit before receive processing is done, this way you won't need a separate synchronization mechanism. Hope this helps.

  1. You created a channel which has 9 buffer space, which means main routine (r1) will not blocked until the 10th element was ready to send to messages.

  2. In your go func() (r2), it most probably starts running when r1 almost finished for r2 is a new routine and system takes time to create stacks etc.

so, r2 doesn't print anything, for r1 is done and program exits while r2 has just begin running.