Sobes.tech
Junior — Middle+

Set the maximum number of concurrent printNumber function calls

livecode

Task condition

Modify the program so that no more than three calls to the printNumber function are executed simultaneously.

package main

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

func main() {
    var wg sync.WaitGroup
    sem := make(chan struct{}, 3) // semaphore limiting the number of concurrent calls

    for idx := 0; idx < 10; idx++ {
        wg.Add(1)
        go func(n int) {
            defer wg.Done()
            sem <- struct{}{}   // acquire a slot
            printNumber(n)
            <-sem               // release the slot
        }(idx)
    }

    wg.Wait()
}

func printNumber(num int) {
    time.Sleep(time.Second)
    fmt.Println(num)
}