Go-channel principle

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

Note: The text is the Channel axioms, the author is Dave Cheney, this is his blog address

Most of the new Go programmers can quickly understand the channel as a queue value and agree that when the channel is full or empty, the operation is the concept of blocking.

This article explores the less common features of Channel Four:

    • Send data to a nil channel, causing permanent blocking
    • Receive data from a nil channel, causing permanent blocking
    • Send data to an already closed channel, causing panic
    • Receives data from an already closed channel and immediately returns a value of 0

Send data to a nil channel, causing permanent blocking

This first example is a bit of a surprise for newcomers, which send data to a nil channel, causing it to block forever.

The following program will cause a deadlock on line 5th because the uninitialized channel is nil and its value is zero

package mainfunc main() {        var c chan string        c <- "let's get started" // deadlock}

Click here to run

Receive data from a nil channel, causing permanent blocking

Similarly, receiving data from a nil channel can cause the recipient to block forever.

package mainimport "fmt"func main() {        var c chan string        fmt.Println(<-c) // deadlock}

Click here to run

Why is this happening? Here's a possible explanation.

    • The size of the channel's buffer is not part of the type declaration, so it must be part of the value of the channel
    • If the channel is not initialized, its buffer size will be 0
    • If the channel's buffer size is 0, then it will not have buffer
    • If the channel does not have buffer, one send will be blocked until another goroutine is ready for reception
    • If the channel is nil and the receiver and sender have no interaction, they will block and wait in their channel and no longer be unblocked

Send data to an already closed channel, causing panic

The following program is likely to be panic, because the first goroutine will close the channel when it reaches 10 when its siblings have time to complete sending their values.

package mainimport "fmt"func main() {        var c = make(chan int, 100)        for i := 0; i < 10; i++ {                go func() {                        for j := 0; j < 10; j++ {                                c <- j                        }                        close(c)                }()        }        for i := range c {                fmt.Println(i)        }}

Click here to run

So why doesn't a close () version allow you to detect if the channel is closed?

if !isClosed(c) {        // c isn't closed, send the value        c <- v}

But this function has an intrinsic rivalry, and someone might close the channel before we check out isClosed (c), but the code gets C <-v.

The method of dealing with this problem is discussed in 2nd article, which is connected at the bottom of the article.

Receives data from an already closed channel and immediately returns a value of 0

This last example is the opposite of the previous one, and once a channel is closed, all its values are lost from buffer, and the channel returns a value of 0 immediately.

package mainimport "fmt"func main() {            c := make(chan int, 3)            c <- 1            c <- 2            c <- 3            close(c)            for i := 0; i < 4; i++ {                        fmt.Printf("%d ", <-c) // prints 1 2 3 0            }}

Click here to run

The correct solution to this problem is to use range cyclic processing:

for v := range c {            // do something with v}for v, ok := <- c; ok ; v, ok = <- c {            // do something with v}

The two statements are equal in the function and show range what to do.

Extended Reading

    • Concurrency isn't Parallelism by Rob Pike
    • Go Concurrency Patterns:pipelines and cancellation
    • Curious Channels
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.