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.