面试题答案
一键面试package main
import (
"fmt"
"sync"
)
func limitConcurrent(task func(int), numTasks int) {
semaphore := make(chan struct{}, 5)
var wg sync.WaitGroup
for i := 0; i < numTasks; i++ {
semaphore <- struct{}{}
wg.Add(1)
go func(index int) {
defer func() {
<-semaphore
wg.Done()
}()
task(index)
}(i)
}
wg.Wait()
}