Home  >  Article  >  Backend Development  >  Golang implements parallelism

Golang implements parallelism

WBOY
WBOYOriginal
2023-05-21 19:12:36552browse

With the rapid development of big data, artificial intelligence and other technologies, the demand for high performance and high concurrency is also getting higher and higher. In this context, golang is very popular as a high-concurrency and high-performance programming language. Among them, golang's parallel feature is one of its important features that distinguishes it from other languages. This article mainly discusses how to implement parallelism in golang and the performance improvements brought by parallelism.

1. Overview of Parallelism

Parallel refers to the execution of multiple tasks at the same time. It does not mean the execution of multiple tasks at the same time. On a single CPU, only one instruction can be executed at a moment, but the execution time of each instruction is very short. The CPU completes multi-tasking from the user's perspective through rapid rotation. This rapid rotation causes the task switching time to become very short, and it looks like multiple tasks are being performed at the same time. This is parallelism.

In practical applications, we usually use parallel technology to handle high-concurrency and high-density business scenarios. By taking advantage of the characteristics of multi-core CPUs, tasks are assigned to multiple cores for simultaneous execution to improve execution efficiency. . In golang, goroutine is called a lightweight thread. It is more lightweight and efficient than a thread, and starting a goroutine requires very little overhead. Therefore, golang is naturally suitable for implementing parallel operations.

2. Goroutine parallelism

In golang, we can implement parallel operations through goroutine. Goroutine is a lightweight thread that is managed by the golang runtime system and does not consume a lot of memory like operating system threads. Therefore, we can start many goroutines at the same time, reduce the waiting time of tasks, and improve program execution. efficiency. Let's take a look at how to start goroutine.

1. Define goroutine

The way to define goroutine in golang is very simple. You only need to add the keyword go before the function body that needs to be executed independently. For example:

go func() {
    fmt.Println("Hello, goroutine!")
}()

2. Start goroutine

Starting goroutine is very simple, just call the function. For example:

func main() {
    go func() {
        fmt.Println("Hello, goroutine!")
    }()
    fmt.Println("Hello, main!")
    time.Sleep(time.Second)
}

In the above code, we start a goroutine to print a sentence, while the main function continues to print its own words and pauses for 1 second. When we run the program at this time, we will see that the main function and goroutine will alternately print out Hello, main! and Hello, goroutine!, which proves that the two functions are executed in parallel in different goroutines.

3. Channel

Channel is an inter-thread communication mechanism provided by golang. Its function is to transfer data between goroutines. A channel has two endpoints, the sending and receiving ends. We can create a channel through the keyword make, and then use <- to transfer data. For example:

func goroutineFunc(c chan int) {
    c <- 1
}

func main() {
    c := make(chan int)
    go goroutineFunc(c)
    result := <-c
    fmt.Println(result)
}

In the above code, we also create a channel c when starting the goroutine, and then use c <- 1 in the goroutine to write 1 to the channel, Finally, read the data through result := <-c. This method can exchange data in different goroutines and achieve large-scale parallel operations.

3. Parallel Computing

If we want to perform parallel computing, we need to allocate computing tasks to different goroutines for execution, and exchange data through channels. Below we use sample code to demonstrate how to use golang to implement parallel computing.

1. Parallel calculation of pi value

func pi(n int) float64 {
    ch := make(chan float64)
    for i := 0; i < n; i++ {
        go func(start, end int) {
            sum := 0.0
            for j := start; j < end; j++ {
                x := (float64(j) + 0.5) / float64(n)
                sum += 4.0 / (1.0 + x*x)
            }
            ch <- sum
        }(i*n/n, (i+1)*n/n)
    }
    result := 0.0
    for i := 0; i < n; i++ {
        result += <-ch
    }
    return result / float64(n)
}

func main() {
    fmt.Println(pi(10000))
}

In the above code, we first create a channel ch with a length of n, and then use n goroutines to calculate and write the calculation results to the channel middle. Finally, we read the sum of all results from the channel and calculate the π value. Through parallel computing, we can greatly increase the speed of calculation.

2. Parallel calculation of matrix multiplication

func MatrixMul(a, b [][]int) [][]int {
    m, n, p := len(a), len(a[0]), len(b[0])
    c := make([][]int, m)
    for i := 0; i < m; i++ {
        c[i] = make([]int, p)
    }

    ch := make(chan int)
    for i := 0; i < m; i++ {
        for j := 0; j < p; j++ {
            go func(x, y int) {
                sum := 0
                for k := 0; k < n; k++ {
                    sum += a[x][k] * b[k][y]
                }
                ch <- sum
            }(i, j)
        }
    }

    for i := 0; i < m; i++ {
        for j := 0; j < p; j++ {
            c[i][j] = <-ch
        }
    }

    return c
}

func main() {
    a := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
    b := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
    fmt.Println(MatrixMul(a, b))
}

In the above code, we use goroutine to calculate the product of matrices in parallel. Allocate computing tasks to goroutines, and then exchange data through channels. Finally we read all the results from the channel and form a product matrix. Through parallel computing, we are able to increase computing speed and reduce computing costs.

Summary

This article mainly introduces how to use goroutine to implement parallel computing in golang, and how to use goroutine and channels. Through parallel computing, we can allocate computing tasks to multiple goroutines to improve program running efficiency and are suitable for handling high-concurrency and high-density business scenarios. Golang's built-in goroutine and channel mechanisms make parallel operations easier and more efficient than other languages.

The above is the detailed content of Golang implements parallelism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:golang node transferNext article:golang node transfer