实现
type Semaphore chan struct{}
func (l *Semaphore) init(size int) {
*l = make(chan struct{}, size)
}
func (l *Semaphore) do(task func()) {
*l <- struct{}{}
task()
defer func() {
select {
case <-*l:
}
}()
}
测试/使用示例
func TestSemaphore(t *testing.T) {
var semaphore Semaphore
semaphore.init(3)
wg := sync.WaitGroup{}
for i := 0; i < 100; i++ {
tab := i
wg.Add(1)
go func() {
defer wg.Done()
semaphore.do(func() {
fmt.Println("task running:", tab)
time.Sleep(time.Second)
fmt.Println("task finish:", tab)
})
}()
}
wg.Wait()
}