Go concurrency without it, just like an iphone without a network

Source: Internet
Author: User

Go concurrency without it, just like an iphone without a network

Brief introduction

The concurrency attribute of Golang is a large kill device of the language, and when it comes Channel to concurrency, you can think of it as a conduit through which the core unit can send or receive data for communication. This article to get a deeper look at the channel.

The channel design is based on the CSP model. CSP is the abbreviation for communicating sequential process, which can be called the communication sequence process and is a concurrent programming model, presented by Tony Hoare in 1977. In simple terms, the CSP model consists of the entities (threads or processes) that are executed concurrently, and the entities communicate by sending messages, which are either channels or channel. The key to the CSP model is to focus on the channel, not the entity that sends the message. The Go language implements the CSP section theory, goroutine corresponds to the entities that are executed concurrently in the CSP, and the channel corresponds to the channel in the CSP.

Create Channel

    • The channel in Go is used chan as a keyword.

    • Unbuffered Chan case, the send and receive will be blocked until the other party is ready. This approach can be used to synchronize in Gororutine, which requires the use of locks or condition variables.

    • With Cushion Chan, you can avoid blocking, improve the performance of your application, and typically change space in time.

aChan := make(chan int)  // 创建无缓冲chanbChan := make(chan int, N) // 创建缓冲为N的chan</pre>

assigning and taking values

It is normal to see no significant effect from the following code, because their two statements are usually not together, for example: The process A sends the data, and the process B receives the data .

mchan <- value  // 发送值v到Channel ch中value := <-mchan // 从Channel ch中接收数据,并将数据赋值给v

Select

Selsect is the most common way to obtain data in the channel.

Select can be somewhat analogous to the select in IO multiplexing in Linux. The latter is equivalent to providing unified management of multiple IO events, while the select in Golang is equivalent to providing unified management of multiple channel. Of course, this is just a use of select on the channel.

func main(){    ch1 := make(chan int, 1)    ch2 := make(chan int, 1)    select {        case e1 := <-ch1:        //如果ch1通道成功读取数据,则执行该case处理语句            fmt.Printf("1th case is selected. e1=%v",e1)        case e2 := <-ch2:        //如果ch2通道成功读取数据,则执行该case处理语句            fmt.Printf("2th case is selected. e2=%v",e2)        default:        //如果上面case都没有成功,则进入default处理流程            fmt.Println("default!.")    }}

For...range

The For ... range statement can handle channel.

    go func() {        time.Sleep(1 * time.Hour)    }()    c := make(chan int)    go func() {        for i := 0; i < 10; i = i + 1 {            c <- i        }        close(c)    }()    for i := range c {        fmt.Println(i)    }    fmt.Println("Finished")

Timeout

One important application of Select is time-out processing. Because the Demo,select statement provided above will always be blocked. At this point we may need a timeout operation to handle the timeout situation. In this example we will send a data to channel C1 in 2 seconds, but Select is set to 1 seconds timeout, so we will print timeout 1 instead of result 1.

    c1 := make(chan string, 1)    go func() {        time.Sleep(time.Second * 2)        c1 <- "result 1"    }()    select {    case res := <-c1:        fmt.Println(res)    case <-time.After(time.Second * 1):        fmt.Println("timeout 1")    }

Close

The go built-in close method can be used to close the channel. However, if the channel has been closed, continuing to send data to it will cause panic:send on closed channel:

close(mChan)

Recommended Reading :
It's better than nothing: Go relies on Administrative tools DEP
工欲善其事, its prerequisite (Go development tool)

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.