Home > Backend Development > Golang > How Can I Control the Number of Concurrent Goroutines in Go?

How Can I Control the Number of Concurrent Goroutines in Go?

Mary-Kate Olsen
Release: 2024-12-27 21:46:11
Original
678 people have browsed it

How Can I Control the Number of Concurrent Goroutines in Go?

Controlling the Number of Concurrent Goroutines

Executing a multitude of goroutines simultaneously can enhance performance in appropriately designed programs. However, in certain scenarios, it becomes necessary to limit the number of concurrently running goroutines. This article explores how to manage the number of goroutines that execute at any given time.

Bounded Parallelism

The "Bounded Parallelism" pattern, as described in the Go Concurrency Patterns article, provides a solution to limiting the number of concurrent goroutines. This pattern utilizes a channel with a limited capacity to control the number of goroutines that can execute simultaneously.

Example Implementation

Consider the following example, where we need to maintain a maximum of 10 concurrent goroutines to process a large number of tasks:

package main

import "fmt"

func main() {
    maxGoroutines := 10
    guard := make(chan struct{}, maxGoroutines) // Capacity of the channel limits concurrent goroutines

    for i := 0; i < 30; i++ {
        guard <- struct{}{} // Blocking operation to prevent exceeding the limit
        go func(n int) {
            worker(n)
            <-guard // Release the guard when the worker completes
        }(i)
    }
}

func worker(i int) { fmt.Println("doing work on", i) }
Copy after login

In this implementation, the guard channel acts as the limiting factor. When the number of concurrent goroutines reaches the maximum capacity of the channel (10), the guard channel blocks new goroutines from starting. Once a running goroutine completes, it releases the guard by receiving from the channel, allowing a new goroutine to execute.

Conclusion

By utilizing the "Bounded Parallelism" pattern and a limited capacity channel, it is possible to control the number of concurrent goroutines, ensuring that a desired maximum is consistently maintained. This approach provides a structured and efficient way to manage parallelism in Go programs.

The above is the detailed content of How Can I Control the Number of Concurrent Goroutines in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template