This is a creation in Article, where the information may have evolved or changed.
The gocontinue usage of Go implements a lightweight thread that can be created massively. Channal communication between threads, the following is the basic usage.
Channal's BUF
C:=make (chan int, 3)
3 is the set of chanal memory, the cache only means that the created channal can be stored at the same time 3 data, does not mean that read channal can be read at the same time.
X:=<-c
Reading Channal is still a blocking way to read the data one at a time.
When there is valid data in the Channal cache, the data in the BUF can still be read even if close channal is dropped. It is important to note that when reading data from the close channal, channal is not blocked, and when the BUF data in channal is read out, it still reads 0 values in a non-blocking manner.
Channal for Range
C:=make (chan int)
For I:=range C {
}
For Rangge, you can take out the data in the channal by blocking the data, which is consistent with the usual way, and it blocks the wait data when the data in the channal is empty.
If, in the case where channal is already close, the for range will read only valid data in the Channal and then proceed down instead of reading 0 as continuously as in the above situation.
Simple test Code
Import(
"FMT"
"Time"
)
FuncMain (){
C: =make (chanint,3)
FMT. Println ("Nobuf")
gotest1 (c)
gotest2 (c)
gotest3 (c)
time. Sleep (3*time. Second)
Close(c)
//fmt. Println (<-c)
fori: =rangec{
FMT. Println (i)
}
//fmt. Println (<-c)
//for I: = range c {
// fmt. Println (i)
//}
}
Functest1 (cChanint){
c<-1
}
Functest2 (cChanint){
c<-2
}
Functest3 (cChanint){
c<-3
}