semaphore: add worker-pool example

I've commented several times in various forums that basically every
time I've seen the “worker goroutine” pattern in Go, there has turned
out to be a cleaner implementation using semaphores.

This change adds a simple such example. (For more complex usage, I
would generally pair the semaphore with an errgroup.Group.)

Change-Id: Ibf69ee761d14ba59c1acc6a2d595b4fcf0d8f6d6
Reviewed-on: https://go-review.googlesource.com/75170
Reviewed-by: Ross Light <light@google.com>
This commit is contained in:
Bryan C. Mills 2017-11-01 15:49:15 -04:00 committed by Bryan Mills
commit fd80eb99c8
3 changed files with 98 additions and 12 deletions

View file

@ -4,13 +4,14 @@
// +build go1.7
package semaphore
package semaphore_test
import (
"fmt"
"testing"
"golang.org/x/net/context"
"golang.org/x/sync/semaphore"
)
// weighted is an interface matching a subset of *Weighted. It allows
@ -85,7 +86,7 @@ func BenchmarkNewSeq(b *testing.B) {
for _, cap := range []int64{1, 128} {
b.Run(fmt.Sprintf("Weighted-%d", cap), func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = NewWeighted(cap)
_ = semaphore.NewWeighted(cap)
}
})
b.Run(fmt.Sprintf("semChan-%d", cap), func(b *testing.B) {
@ -116,7 +117,7 @@ func BenchmarkAcquireSeq(b *testing.B) {
name string
w weighted
}{
{"Weighted", NewWeighted(c.cap)},
{"Weighted", semaphore.NewWeighted(c.cap)},
{"semChan", newSemChan(c.cap)},
} {
b.Run(fmt.Sprintf("%s-acquire-%d-%d-%d", w.name, c.cap, c.size, c.N), func(b *testing.B) {