GO using channel for synchronization (channel 1)

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Always try to follow the tutorial to understand the use of channel and the significance of specific existence. According to the personal understanding, the channel is mainly used to achieve data synchronization and interaction between different goroutine.

Basic knowledge of channel:

Channel is a type of pipe that can be sent or received with the channel operator <-.

CH <-V//V is fed into channel ch.
V: = <-ch//is received from CH and assigned to V.
(the arrow is the direction of the data flow.) )
Like map and slice, the channel must be created before it is used:
CH: = make (chan int)

By default, both send and receive are blocked until the other end is ready. This allows the goroutine to synchronize without a definite lock or race variable.

The code is as follows:

Package Mainimport "FMT" func sum (a []int, C Chan int) {sum: = 0for _, V: = range a {sum + = v}c <-sum//Send sum to C} Func Main () {a: = []int{7, 2, 8,-9, 4, 0}c: = make (chan int) go sum (A[:len (a)/2], C) Go sum (A[len (a)/2:], c)/* The code below will ensure that until two RO Utine result output to C, continue to execute, so as to achieve the effect of synchronization */x, y: = <-c/* The first channel is filled after the assignment */, <-C/* The second channel is filled after the assignment */      FMT. Println (x, Y, X+y)}


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.