简体   繁体   中英

Golang concurrency and blocking with a single channel, explanation needed

I'm playing around with the code presented on https://tour.golang.org/concurrency/5 . My idea was that I could simplify the code by getting rid of the quit channel and still keep the correct program behavior - just for learning purposes.

Here is the code I've got (simplified it even more for better readability):

package main

import "fmt"
import "time"

func sendNumbers(c chan int) {  
    for i := 0; i < 2; i++ {
        c <- i
    }
}

func main() {
    c := make(chan int)
    go func() {
        for i := 0; i < 2; i++ {
            fmt.Println(<-c)
        }
    }()
    time.Sleep(0 * time.Second)
    sendNumbers(c)
}

In this code, the go routine I spawn should be able to receive 2 numbers before it returns. The sendNumbers() function I call next sends exactly 2 numbers to the channel c.

So, the expected output of the program is 2 lines: 0 and 1. However, what I'm getting when I run the code on the page, is just a single line containing 0.

Note the

time.Sleep(0 * time.Second) 

though that I deliberately added before calling sendNumbers(c). If I change it to

time.Sleep(1 * time.Second) 

The output becomes as expected:

0
1

So, I'm confused with what happens. Can someone explain what is going on? Shouldn't both sends and receives block regardless of how much time is passed before I call sendNumbers()?

In Go, the program exits as soon as the main function returns regardless of whether other goroutines are still running or not. If you want to make sure the main function does not exit prematurely, you need some synchronization mechanism. https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/
You don't absolutely have to use synchronization primitives, you could also do it with channels only, arguably a more idiomatic way to do it.

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