Conversation
6ed4a98 to
47016ba
Compare
47016ba to
88cda2a
Compare
|
A semaphore is usually used to constrain the parallelism of a concurrent operation to less than its theoretical maximum concurrency. For example, if you need to make a bunch of GET requests, but only want 3 in-flight at once, you might do semaphore := make(chan struct{}, 3)
for _, url := range urls {
go func(url string) {
semaphore <- struct{}{} // acquire
defer func() { <-semaphore }() // release
resp, err := http.Get(url)
// ...
}(url)
}Semaphores just have those two operations — acquire, and release. I think you misinterpret the Wiki definition when it mentions wait — that doesn't map to an operation, but rather describes what happens when a goroutine tries to acquire on a semaphore that's already at capacity. What you've created here isn't precisely a semaphore. You're just using a channel as a counter! It works. But I bet there's a much easier way to do what you're trying to do, with a lot less code :) |
|
@peterbourgon thanks for your comments, what you said it's right. It is a semaphore hybrid wrapped into a struct. I will try to pull apart the wait method by segregating interfaces. Thanks! |
No description provided.