This is a creation in Article, where the information may have evolved or changed.
The channel will block, and the system will continue to call other Goroutine,main () when it is blocked, but it is also a goroutine, which is executed first.
Look at a code:
Package Mainimport ( "FMT") Func display (msg string, C chan bool) { FMT. PRINTLN (msg) C <-true FMT. Printf ("End%s \ n", msg)}func main () { c: = Make (chan bool) go display ("Hello", c) go display ("Hello1", c)
go display ("Hello2", c) FMT. Println ("Start") <-c FMT. Println ("End")}
This code outputs the result:
Starthelloend Hellohello1hello2end
First executes the main function, which is the first goroutine, and in main it creates 3 goroutine through the GO statement, but is not executed immediately, they must wait until main hangs before being called.
When main executes to <-c, depending on the channel feature, there is a blocking at this time, the system will hang the main goroutine, continue to call the other goroutine, that is, the previous 3 Goroutine created, starting from the first.
Execute to: Go display ("Hello", c)
At this time first print out Hello, the random function of C <-true because main is already waiting to accept, so this send success, continue to execute the following code to print out end Hello, and because the receiver main also received information, The Goroutine block of main is canceled, activated, and can be called again.
However, the main is not called immediately, because although main is reactivated, it has been queued to the back of the remaining two goroutine, so the goroutine that will actually continue to execute is go display ("Hello1", c).
In Go display ("Hello1", c), Hello1 is first printed out, random C <-true like the channel sends a message, but because there is no receiver (main has been received), so this goroutine is also blocked, The system continues to call the next goroutine, the same as only output Hello2, and finally call main goroutine, print out end.
The above is a non-buffered channel, the blocking principle of buffering is not the same as this.