Junior — Senior
Control the number of simultaneous executions of the printNumber function without modifying it
livecode
Task condition
It is necessary to implement a limiter that prevents the printNumber function from executing more than five times simultaneously, without modifying the function itself.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
wgGroup := sync.WaitGroup{}
sem := make(chan struct{}, 5)
for idx := 0; idx < 10; idx++ {
wgGroup.Add(1)
go func(num int) {
defer wgGroup.Done()
printNumber(sem, num)
}(idx)
}
wgGroup.Wait()
close(sem)
}
func printNumber(ch chan struct{}, n int) {
ch <- struct{}{}
time.Sleep(time.Second)
fmt.Println(n)
<-ch
}