I. Concepts
Channel is the communication mode between goroutine provided by golang language.
Goroutine runs in the same address space, so the shared memory access must be synchronized. So how does goroutine communicate data? Go provides a good communication mechanism channel. A channel can be analogous to a two-way channel in a Unix shell: it can be used to send or receive values. These values can only be of a specific type: channel type. When defining a channel, you also need to define the type of value sent to the channel.
Ii. Declaration Method
VaR channame Chan elementtype var ch Chan int use make, you can specify the channel capacity CH = make (Chan INT)
3. Channel read and write
The channel receives and sends data through the operator <-
Ch <-V // send V to channel Ch. Write Data V: = <-ch // from the interface data in CH, and assign value to V to read data
By default, channel receiving and sending data are blocked, unless the other end is ready, so that the goroutines synchronization becomes simpler, without explicit lock. The so-called blocking means that if you read (value: = <-Ch), it will be blocked until data is received. Second, any sending (CH <-5) will be blocked until the data is read. The unbuffered channel is a great tool for synchronizing between multiple goroutines.
Iv. Code
Package mainimport ("FMT" "strconv") // defines an addition function and transmits the channel type. After each calculation, quit adds 1 func add (X, Y int, quit Chan INT) {z: = x + y FMT. println (z) // write data quit <-1} // receives the data and assigns it to func read (CH Chan INT) {value: = <-ch FMT. println ("value" + strconv. ITOA (value)} func write (CH Chan INT) {// ch <-10} func main () {// defines a channel-type slice array CHS: = make ([] Chan int, 10) // execute the addition function cyclically for I: = 0; I <10; I ++ {// get a channel CHS [I] = make (Chan INT) // execute goroutine and send a channel type data go add (I, I, CHS [I])} For _, V: = range CHS {// interface channel type data <-V }}
Golang concurrent programming-Channel