Home > Backend Development > Golang > Concurrency modes in Golang: Channels and Pipelines

Concurrency modes in Golang: Channels and Pipelines

王林
Release: 2023-08-09 10:05:05
Original
1505 people have browsed it

Golang 中的并发模式之 Channels 和 Pipelines

Concurrency mode in Golang: Channels and Pipelines

In Golang, we can use goroutine to implement concurrent programming. In actual development, we often need to handle the data flow of concurrent tasks. Golang provides two concurrency modes, channels and pipelines, to handle this situation.

Channels are a very powerful concurrency primitive in Golang, used to pass data between goroutines. It ensures synchronization and secure delivery of data. By sending and receiving data on a channel, we ensure order and synchronization between goroutines.

Pipelines is a concurrency mode that processes data flow by connecting multiple goroutines. Each goroutine has input and output channels, and by chaining them together, data can flow and be processed between all goroutines.

First, let’s look at the basic usage of channels. In Golang, you can use the make() function to create a channel.

ch := make(chan int)
Copy after login

We can use the <- operator to send data to the channel, for example:

ch <- 10
Copy after login

and use the <- operator Receive data from the channel, for example:

x := <-ch
Copy after login

Please note that the receive operation will be blocked until data is available. The send operation will also be blocked until other goroutine is ready to receive data.

The following is a simple example that uses a channel to send the generated random numbers to another goroutine:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    ch := make(chan int)

    go randomGenerator(ch) // 启动生成随机数的 goroutine

    // 等待接收随机数并打印
    for i := 0; i < 10; i++ {
        num := <-ch
        fmt.Println("Received random number:", num)
        time.Sleep(1 * time.Second)
    }
}

func randomGenerator(ch chan int) {
    for {
        // 生成随机数并发送到 channel
        num := rand.Intn(100)
        ch <- num
    }
}
Copy after login

In the above example, we passrandomGenerator() The function generates a random number and sends it to the ch channel. The main function receives random numbers from the channel and prints them.

Next, let us introduce the concurrency mode of pipelines. A pipeline contains multiple goroutines, and by cascading them together, a network can be built to process the data flow.

Suppose we have a list of numbers and we want to square each number in the list and print the result. We can use two goroutines to implement this functionality: one to calculate the square and another to print the result.

package main

import (
    "fmt"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    input := make(chan int)
    output := make(chan int)

    // 启动计算平方的 goroutine
    go square(input, output)

    // 启动打印结果的 goroutine
    go printer(output)

    // 将数字发送到 input channel
    for _, num := range numbers {
        input <- num
    }

    // 关闭 input channel,表示数据发送完毕
    close(input)

    // 等待所有结果被打印
    <-output
}

func square(input chan int, output chan int) {
    for num := range input {
        // 计算平方,并发送结果到 output channel
        result := num * num
        output <- result
    }

    // 关闭 output channel,表示计算完毕
    close(output)
}

func printer(output chan int) {
    for result := range output {
        // 打印结果
        fmt.Println("Result:", result)
    }

    // 发送信号表示输出完毕
    output <- 0
}
Copy after login

In the above example, we first create an input channel and an output channel. Then we started two goroutines: square() is used to calculate the square operation and sends the result to the output channel, printer() is used from output Receive the result in the channel and print it.

In the main function, we use a for loop to send the number into the input channel. Then we close the input channel, indicating that the data is sent. Finally we wait to receive a signal from the output channel, indicating that all results have been printed.

By using channels and pipelines, we can easily implement concurrent processing of data streams. They provide Golang with a powerful and concise way of concurrent programming, allowing us to handle concurrent tasks efficiently. Whether it is simple data transfer or complex data processing network, these two concurrency modes can help us write efficient and reliable concurrent programs.

The above is the detailed content of Concurrency modes in Golang: Channels and Pipelines. For more information, please follow other related articles on the PHP Chinese website!

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