Sobes.tech
Junior — Middle

Is it possible to set a limit on the number of goroutines running simultaneously in a program?

sobes.tech AI

Answer from AI

The Go language does not have a built-in mechanism to set a strict limit on the number of goroutines running simultaneously. Goroutines can be numerous, and their scheduling and switching are managed by the Go runtime.

However, if you need to limit the number of goroutines executing at the same time (for example, to control resource usage), you can use semaphores or channels to limit parallelism.

An example of limiting the number of concurrently running goroutines using a channel:

package main

import (
    "fmt"
    "sync"
)

func worker(id int, sem chan struct{}, wg *sync.WaitGroup) {
    defer wg.Done()
    sem <- struct{}{} // acquire resource
    fmt.Printf("Goroutine %d started work\n", id)
    // ... work ...
    fmt.Printf("Goroutine %d finished work\n", id)
    <-sem // release resource
}

func main() {
    const maxGoroutines = 5
    sem := make(chan struct{}, maxGoroutines)
    var wg sync.WaitGroup

    for i := 0; i < 20; i++ {
        wg.Add(1)
        go worker(i, sem, &wg)
    }

    wg.Wait()
}

In this example, no more than 5 goroutines will run simultaneously.

Is it possible to set a limit on the number of… - sobes.tech