This is a creation in Article, where the information may have evolved or changed.
The channel is blocked by default, that is, if the channel is full, it blocks the write, and if the channel is empty, it blocks the read. Blocking means waiting until it's your turn. We will sometimes receive fatal Error:all Goroutines is asleep-deadlock! Exception, how is this?
code example:
Package Main
Import "FMT"
Func Main () {
Channel: = Make (Chan string, 2)
Fmt. Println ("1")
Channel <-"H1"
Fmt. Println ("2")
Channel <-"W2"
Fmt. Println ("3")
Channel <-"C3"//Perform this step and report the error directly
Fmt. Println ("...")
MSG1: = <-channel
Fmt. Println (MSG1)
}
Execution effect:
Reference:
Http://stackoverflow.com/questions/26927479/go-language-fatal-error-all-goroutines-are-asleep-deadlock
Fatal Error:all Goroutines is asleep-deadlock!
The meaning of the error message is:
In main Goroutine line, expect to get a data from the pipeline, and this data must be other Goroutine line into the pipeline
But other goroutine lines have been executed (all goroutines is asleep), then no data will ever be put into the pipeline.
So, the main Goroutine line is waiting for a data that will never come, and the whole program will wait forever.
This is obviously no result, so the program said "forget it, do not insist, I myself suicide, reported a mistake to the code author, I was deadlock."
Here is the system automatically in addition to the main process of the process is closed, do the check, and then reported the error, proof the idea is as follows, in 100 seconds, we can not see the exception, 100 seconds after the system error.
Package Main
Import (
"FMT"
"Time"
)
Func Main () {
Channel: = Make (Chan string, 2)
Go func () {
Fmt. Println ("Sleep 1")
Time. Sleep (* time. Second)
Fmt. Println ("Sleep 2")
}()
Fmt. Println ("1")
Channel <-"H1"
Fmt. Println ("2")
Channel <-"W2"
Fmt. Println ("3")
Channel <-"C3"
Fmt. Println ("...")
MSG1: = <-channel
Fmt. Println (MSG1)
}
Performance in 100 seconds:
After 100 seconds, perform the effect:
What if you avoid throwing the above exception? At this time we can use Select to help us deal with.
Package Main
Import "FMT"
Func Main () {
Channel: = Make (Chan string, 2)
Fmt. Println ("1")
Channel <-"H1"
Fmt. Println ("2")
Channel <-"W2"
Fmt. Println ("3")
Select {
Case Channel <-"C3":
Fmt. Println ("OK")
Default
Fmt. PRINTLN ("Channel is full!")
}
Fmt. Println ("...")
MSG1: = <-channel
Fmt. Println (MSG1)
}
Execution effect:
At this time, we abandoned the third Chan to write.
The example above is a written example, as well as the example read, the following exception is the WS: = <-channel This line is thrown.
Channel: = Make (Chan string, 2)
Fmt. PRINTLN ("Begin")
WS: = <-channel
Fmt. PRINTLN (WS)