Home > Backend Development > Golang > What is channel in Go language?

What is channel in Go language?

WBOY
Release: 2023-06-10 13:57:08
Original
1633 people have browsed it

The channel in the Go language is a special data structure that can be used to implement communication and synchronization between different goroutines. It is one of the core components of the Go language concurrency model and the most important concurrency primitive in the Go language.

So, why is channel so important? Because the concurrency model of the Go language is essentially based on the CSP (Communicating Sequential Processes) model, and channel is the channel in the CSP model, its role is similar to a pipe, used to transfer data between different goroutines, which makes goroutines Data synchronization becomes very convenient.

In the Go language, you can create a channel using the built-in make function and specify the type of channel element and the size of the buffer (if necessary):

ch := make(chan int)        // 创建一个无缓冲的 channel
ch2 := make(chan string, 10)  // 创建一个带有缓冲区的 string 类型的 channel,缓冲区大小为 10
Copy after login

You can see that if not If the buffer size is specified, the channel is unbuffered. This means that when a goroutine reads data from an unbuffered channel, it blocks until another goroutine writes data to the channel. Correspondingly, when a goroutine writes data to an unbuffered channel, it blocks until another goroutine reads data from the channel.

In contrast, a buffered channel can perform non-blocking write operations when the buffer is not full, and will only block when the buffer is full. Likewise, a buffered channel can perform non-blocking read operations when the buffer is not empty, blocking only when the buffer is empty.

In the Go language, passing data through channels is very simple. For example, the following code shows how to create 2 goroutines, one goroutine sends some data to the channel, and the other goroutine receives data from the channel and prints it:

package main

import "fmt"

func sender(ch chan int) {
    ch <- 10
    ch <- 20
    ch <- 30
    close(ch)
}

func receiver(ch chan int) {
    for {
        val, ok := <- ch
        if !ok {
            break
        }
        fmt.Println(val)
    }
}

func main() {
    ch := make(chan int)
    go sender(ch)
    go receiver(ch)
    fmt.Scanln()
}
Copy after login

In the above code, we create a named is the channel of ch and passes it to the two goroutines of sender and receiver. The sender goroutine sends three integer values ​​to ch, and then closes the channel, indicating that the sending of data has ended. The receiver goroutine receives integer values ​​from ch and prints each value. At the end, we use fmt.Scanln() to block the main goroutine to ensure that the program does not exit.

It should be noted that when a channel is closed, the goroutine reading data from it will immediately obtain a zero value without blocking. So in the above code, we use a for loop to continuously read data from the channel, and the loop will end when the channel is closed.

In addition to ordinary channels, the Go language also provides channels with select statements. The select statement can be used to select among multiple channels. Once any channel is ready, the corresponding operation will be performed immediately. Here is a simple example:

package main

import "fmt"

func main() {
    ch1 := make(chan int)
    ch2 := make(chan int)

    go func() {
        ch1 <- 10
    }()

    go func() {
        ch2 <- 20
    }()

    select {
    case val := <- ch1:
        fmt.Println("Received value from ch1:", val)
    case val := <- ch2:
        fmt.Println("Received value from ch2:", val)
    }
}
Copy after login

In the above code, we created two channels ch1 and ch2 respectively and sent some data to them. In the main goroutine, we use select statement to select a prepared channel from two channels and print out the value received from the channel. In this example, since the data in ch1 arrives first, select will select ch1 first.

In summary, channel in Go language is a very important concurrency primitive that can be used to achieve communication and synchronization between goroutines. Using channels can make concurrent programming simple and elegant, especially in some complex concurrency scenarios, the role of channels is particularly obvious.

The above is the detailed content of What is channel in Go language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template