Home > Backend Development > Golang > Concurrency control in Golang and Go WaitGroup

Concurrency control in Golang and Go WaitGroup

WBOY
Release: 2023-09-29 20:15:46
Original
693 people have browsed it

Golang中的并发控制和Go WaitGroup

Concurrency control in Golang and Go WaitGroup

In Golang, we can use goroutine to implement concurrent execution tasks. However, in some cases, we need to control the number of concurrent executions to avoid excessive resource consumption or concurrency contention issues. Golang provides some methods to achieve concurrency control, the most commonly used of which is to use Go WaitGroup.

Go WaitGroup is a counting semaphore used to wait for a group of goroutines to complete execution. When we start a group of goroutines, we can use WaitGroup to track the status of these goroutines and perform the next step after all goroutines are completed.

Below we use a specific code example to demonstrate concurrency control in Golang and the use of Go WaitGroup.

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    numWorkers := 5
    var wg sync.WaitGroup

    for i := 0; i < numWorkers; i++ {
        wg.Add(1) // 每启动一个goroutine,等待组加1
        go worker(i, &wg)
    }

    wg.Wait() // 等待所有goroutine完成

    fmt.Println("All workers have finished")
}

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done() // goroutine执行完毕,等待组减1
    
    fmt.Printf("Worker %d started
", id)
    time.Sleep(time.Second) // 模拟耗时操作
    fmt.Printf("Worker %d finished
", id)
}
Copy after login

In this example, we have 5 goroutines, and the task of each execution is to call the worker function. First, we defined a WaitGroup variable wg and started 5 goroutines in the main function. Each goroutine calls the worker function and operates the WaitGroup by passing a pointer to wg.

In the worker function, we use defer wg.Done() to reduce the count of the waiting group after the goroutine completes execution. This means that each goroutine will call the Done() function to notify the WaitGroup when it is completed. Then, we added some simulated time-consuming operations to each worker function to observe the effect of concurrent execution.

In the main function, we call wg.Wait() to wait for all goroutines to complete. This will cause the main function to block after all goroutines have finished executing, until the WaitGroup count reaches zero.

Run the above code, you will see output similar to the following:

Worker 0 started
Worker 1 started
Worker 2 started
Worker 3 started
Worker 4 started
Worker 3 finished
Worker 2 finished
Worker 0 finished
Worker 1 finished
Worker 4 finished
All workers have finished
Copy after login

As can be seen from the output, all goroutines start and run in a concurrent manner, and are notified after completion main function.

By using Go WaitGroup, we can easily control the number of concurrent executions and perform subsequent operations after all goroutines are completed. This is very helpful for handling large-scale concurrent tasks or limiting resource consumption.

To sum up, concurrency control and Go WaitGroup in Golang are important tools for implementing concurrent programming. We can use WaitGroup to track and control the execution of a group of goroutines to ensure the correctness and stability of concurrent operations. In this way, we can better utilize multi-core processors and resources and improve program execution efficiency.

The above is the detailed content of Concurrency control in Golang and Go WaitGroup. 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