A simple example of using Chan in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Development environment: Windows7 64-bit, editor: Sublime Text3

Summary: Go can create a buffered Chan (for example: C1:=make (Chan int,4) is a buffer size of 4 chan), you can also create a non-buffered Chan (such as: C2:=make (chan int) is not buffered Chan).

The code is as follows, with comments in the code:

Package Main


Import (
"FMT"
)


Func Main () {
c: = make (chan int, 2)//Create buffered Chanel, buffer size is 2


This invokes the function, then F1 and F2 are executed concurrently.
Go F1 (c)//pass parameter C to F1 ()
Go F2 (c)//pass parameter C to F2 ()


C1: = <-c
C2: = <-c the//main function exits main () only if it receives two values from C, otherwise the main () will block this until there is data in C that can be received
Fmt. Printf ("c1:%d c2:%d", C1, C2)
}


Func F1 (c Chan int) {//Chan int} indicates that the type of the parameter is a Chanel that stores the int type
C <-1//pass 1 to this Chanel, then main () will accept 1
}


Func F2 (c chan int) {//Chan int} indicates that the type of the parameter is a Chanel that stores the int type
C <-2//2 is passed into this Chanel, then main () will receive 2
}


The result of the run (the result shows that the value of C1 is 2 instead of the 1,C2 value is 1 instead of 2):

Related Article

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.