-
-
Save zhenzou/21f4f1e585105540050f14c8e5cd5d6a to your computer and use it in GitHub Desktop.
pool.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
// 一开始只有一个地方需要限制并发,简单处理 | |
ch := make(chan struct{}, 10) | |
for i := 0; i < 1000; i++ { | |
ch <- struct{}{} | |
go func() { | |
defer func() { | |
<-ch | |
}() | |
doSomething() | |
}() | |
} | |
// 然后有多个地方需要限制并发,复用一下代码,形成 semaphore 提供语义化的 API | |
sema := semaphore.NewWeighted(10) | |
for i := 0; i < 1000; i++ { | |
sema.Acquire(context.Background()) | |
go func() { | |
defer sema.Release(1) | |
doSomething() | |
}() | |
} | |
// 然后还是发现,使用 semaphore,样板代码太多了,直接使用一个 pool 简洁很多 | |
pool := NewPool(10) | |
for i := 0; i < 1000; i++ { | |
pool.Go(doSometing) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment