Goroutine和for循环

All I want to do is to send one value to the channel and return from the main() function and exit the program right after I receive one value from the channel ch.

But this keeps running forever:

ch := make(chan int)

for {
    go func() {
        ch <- 1
    }()
}

<-ch

How do I return with this for loop after I receive one value from the channel?

And why does this run forever?

Go playground link is here

http://play.golang.org/p/EvmT6Pw96Y

Since the for loop runs forever, your code runs forever. Receiving from ch after the for loop is never reached.

If you want your code to exit sometime, you have to end the for loop sometime, e.g. make it run only a certain number of iterations:

for i := 0; i < 5; i++ {
    ...
}

So if you only run 5 iterations (like in my example), after the for loop receiving from ch will be executed which may block (because ch is unbuffered) if other goroutines have not yet run, and at least one of the started goroutines will be executed which sends a value on the channel which may trigger the main goroutine to continue (because its blocking operating is no longer blocking).

Also note that the Go Memory Model only guarantees that certain events happen before other events, you have no guarantee how 2 concurrent goroutines are executed. You have no guarantee that the goroutines started in the for loop will start to execute before the main goroutine gets blocked at receiving from ch.

Usually when a goroutine gets blocked (e.g. blocking channel receive operation), the runtime may schedule another goroutine to run.