Golang channal in BUF and for range some usage

Source: Internet
Author: User
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
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.