Home > Backend Development > Golang > Concurrent Programming Guide: Exploring Parallelism in the Golang Standard Library

Concurrent Programming Guide: Exploring Parallelism in the Golang Standard Library

WBOY
Release: 2024-01-20 09:08:12
Original
1194 people have browsed it

Concurrent Programming Guide: Exploring Parallelism in the Golang Standard Library

Concurrent Programming Guide in Golang Standard Library

Introduction:
Concurrent programming is an important means to solve program performance problems and achieve efficient use of computing resources. In the Golang programming language, a wealth of concurrent programming tools and methods are provided. This article will introduce some common concurrent programming techniques in the Golang standard library, and illustrate their usage and precautions through specific code examples.

  1. Goroutine (coroutine)
    Goroutine is a lightweight thread in Golang, started by the Go keyword. Through Goroutine, we can execute multiple tasks at the same time in the program to achieve high concurrency execution effects. The following is a simple Goroutine example:
package main

import (
    "fmt"
    "time"
)

func printNumbers() {
    for i := 0; i < 5; i++ {
        fmt.Printf("%d ", i)
        time.Sleep(time.Millisecond * 500)
    }
}

func printLetters() {
    for i := 'A'; i < 'F'; i++ {
        fmt.Printf("%c ", i)
        time.Sleep(time.Millisecond * 500)
    }
}

func main() {
    go printNumbers()    // 启动一个Goroutine,打印数字
    go printLetters()    // 启动另一个Goroutine,打印字母

    time.Sleep(time.Second * 3)    // 等待两个Goroutine执行完毕
    fmt.Println("Done")
}
Copy after login

In the above code, we define two functions printNumbers and printLetters respectively, and pass ## The #go keyword starts them as two Goroutines respectively. Use the time.Sleep function to wait for the two Goroutines to complete execution. You can see that numbers and letters are output alternately in the output results.

    Channel (channel)
  1. In Golang, communication between Goroutines is completed using Channel (channel). Channel is a type-safe queue used to pass data between Goroutines. The following is a simple Channel example:
  2. package main
    
    import (
        "fmt"
        "time"
    )
    
    func worker(id int, jobs <-chan int, results chan<- int) {
        for job := range jobs {
            fmt.Printf("Worker %d started job %d
    ", id, job)
            time.Sleep(time.Second)
            fmt.Printf("Worker %d finished job %d
    ", id, job)
            results <- job * 2
        }
    }
    
    func main() {
        numJobs := 5
        jobs := make(chan int, numJobs)
        results := make(chan int, numJobs)
    
        numWorkers := 3
        for w := 1; w <= numWorkers; w++ {
            go worker(w, jobs, results)
        }
    
        for j := 1; j <= numJobs; j++ {
            jobs <- j
        }
        close(jobs)
    
        for a := 1; a <= numJobs; a++ {
            result := <-results
            fmt.Println("Result:", result)
        }
    }
    Copy after login
In the above code, we define the

worker function, which is used to receive the number passed in by the jobs channel and perform the corresponding Processing, the results are returned through the results channel. In the main function, we created two channels, jobs and results, respectively, and passed the jobs channel to three Goroutines for execution. Then, send 5 jobs to the jobs channel through a for loop and close the channel. Finally, the return result of the results channel is received through the for loop and output.

    WaitGroup (waiting group)
  1. In concurrent programming, it is often necessary to wait for all executions of multiple Goroutines to be completed before proceeding to the next step. The
    sync package in Golang provides the WaitGroup type to implement this function. The following is an example of using WaitGroup:
  2. package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func worker(id int, wg *sync.WaitGroup) {
        defer wg.Done()
        fmt.Printf("Worker %d starting
    ", id)
        time.Sleep(time.Second)
        fmt.Printf("Worker %d done
    ", id)
    }
    
    func main() {
        var wg sync.WaitGroup
    
        numWorkers := 3
        wg.Add(numWorkers)
        for w := 1; w <= numWorkers; w++ {
            go worker(w, &wg)
        }
    
        wg.Wait()
        fmt.Println("All workers done")
    }
    Copy after login
    In the above code, we define the

    worker function, which receives a WaitGroup parameter, executes the corresponding task, and executes the task After the execution is completed, the WaitGroup is notified through the Done method. In the main function, we create a WaitGroup variable and specify the number of Goroutines to wait for through the Add method. Then, use the go keyword to start the corresponding number of Goroutines and pass the WaitGroup pointer to each Goroutine. Finally, wait for all Goroutine execution to complete through the Wait method.

    Summary:

    Through the concurrent programming tools and methods provided in the Golang standard library, we can easily implement high-concurrency programs. This article introduces common concurrent programming techniques such as Goroutine, Channel, and WaitGroup, and illustrates them with specific code examples. I hope that readers can better master the concurrent programming skills in Golang and improve the performance and operating efficiency of the program through studying this article.

    The above is the detailed content of Concurrent Programming Guide: Exploring Parallelism in the Golang Standard Library. 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