Go concurrency programming--channel

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

I've never been in touch with concurrent programming before, so write and learn.

Introduction of Channel

Package Mainimport (        "FMT"        "Sync" "        runtime"       ) var counter int = 0func Count (lock *sync. Mutex) {    lock. Lock ()    counter++    FMT. Println (counter)    lock. Unlock ()}func main () {    Lock: = &sync. mutex{} for    i:=0;i<100;i++{        go Count (lock)    }    for{        lock. Lock ()        C:=counter        lock. Unlock ()        runtime. Gosched ()        if c>=100{            break        }}    }

Add counter from 0 to 10

But the above approach is too complex to always reference the lock, so referencing the channel


Package Mainimport "FMT" func Count (ch Chan int) {    ch <-1    fmt. Println ("Counting")}func main () {    CHS: = make ([]chan int, ten) for    i:=0;i<10;i++{        Chs[i]=make (chan int)        go Count (chs[i])    }    For _,ch: = Range (CHS) {        <-ch    }    fmt. Println (CHS)}

The simple explanation is that we write a data to the corresponding channel through the CH <-1 statement. This operation is blocked until the channel is read.

After all the goroutine started, we read the data sequentially from the 10 channel through the <-CH statement. This operation is also blocked before the corresponding channel is written to the data.

This replaces the use of the lock with this operation.


The channel is described in more detail below:

1. Basic syntax:

Declare a channel

var ch chan intvar M map[string] Chan bool

Define a channel

S: = make (chan int)

In the use of channel, the most common include write and read out. The syntax for writing (sending) a data to the channel is straightforward, as follows:

CH <-Value

Writing data to the channel usually causes the program to block until another goroutine reads the data from the channel. The syntax for reading data from the channel is

Value: = <-ch

If the channel does not write data before, reading the data from the channel also causes the program to block until the data is written to the channel.

2.select:

Select is used to monitor a series of file handles, and once a file handle has an IO operation, the Select () call is returned

Note here that you must define the channel before you can use ch: = Make (chan int, 1) for {select {case ch <-0:case ch <-1:}i: = <-chfmt. Println ("Value Received:", I)}

3. Buffering mechanism:

c: = make (chan int, 1024)

This way, even without the reader, you can always write to the channel until the buffer is filled

You can use the range key for easier loop reading:

Here do not know why always error!!!!

For I: = Range c{fmt. Println (i)}

Overall procedure

     c: = make (chan int, ten) for    i:=0;i<10;i++{      c<-12       }    fmt. Println (Len (c)) for         J: = Range c{         fmt. Println (j)       }

4. Timeout mechanism:

In the process of concurrent programming communication, the most need to deal with is the time-out problem, that is, when writing data to the channel to find the channel is full,

Or when the channel is trying to read data, the channel is found to be empty.

If these conditions are not handled correctly, it is likely that the entire goroutine will be locked down. That deadlock happen!

i:= <-ch

This statement has a value in ch write, no problem, once CH is empty, there is no value to write, there will be a deadlock.

Therefore, timeout is a very practical method, in the go language, the main is to borrow the SELECT statement to simulate the timeout

Timeout: = Make (chan bool,1) Ch: =make (chan int) go func () {time.sleep (1) timeout<-true} () Select{case <-ch:case < -timeout:}

5. One-way channel:

Declaration of unidirectional channel variables

var ch1 chan int//Ch1 is a normal channel, not one-way var ch2 chan<-float64//CH2 is unidirectional channel, only used to write float64 data var CH3 <-chan int//Ch 3 is a one-way channel, only for reading int data

Initialization of one-way channel

CH4: = make (chan int) Ch5: = <-chan int (CH4)//CH5 is a one-way read channelch6: = chan<-int (CH4)//CH6 is a one-way write channel

How to use

Func Parse (ch <-chan int) {for value: = Range ch {fmt. PRINTLN ("Parsing value", value)}}

6. Close Channel

Closing the channel is simple, using the go language's built-in close () function directly:
Close (CH)

Determine if a channel has been closed and can use multiple return values at read time:
X, OK: = <-ch
The second bool return value is false to indicate that CH has been closed





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.