1 // Copyright 2017 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 "golang.org/x/sync/semaphore"
16 // Example_workerPool demonstrates how to use a semaphore to limit the number of
17 // goroutines working on parallel tasks.
19 // This use of a semaphore mimics a typical “worker pool” pattern, but without
20 // the need to explicitly shut down idle workers when the work is done.
21 func Example_workerPool() {
25 maxWorkers = runtime.GOMAXPROCS(0)
26 sem = semaphore.NewWeighted(int64(maxWorkers))
30 // Compute the output using up to maxWorkers goroutines at a time.
32 // When maxWorkers goroutines are in flight, Acquire blocks until one of the
34 if err := sem.Acquire(ctx, 1); err != nil {
35 log.Printf("Failed to acquire semaphore: %v", err)
41 out[i] = collatzSteps(i + 1)
45 // Acquire all of the tokens to wait for any remaining workers to finish.
47 // If you are already waiting for the workers by some other means (such as an
48 // errgroup.Group), you can omit this final Acquire call.
49 if err := sem.Acquire(ctx, int64(maxWorkers)); err != nil {
50 log.Printf("Failed to acquire semaphore: %v", err)
56 // [0 1 7 2 5 8 16 3 19 6 14 9 9 17 17 4 12 20 20 7 7 15 15 10 23 10 111 18 18 18 106 5]
59 // collatzSteps computes the number of steps to reach 1 under the Collatz
60 // conjecture. (See https://en.wikipedia.org/wiki/Collatz_conjecture.)
61 func collatzSteps(n int) (steps int) {
63 panic("nonpositive input")
66 for ; n > 1; steps++ {
68 panic("too many steps")
76 const maxInt = int(^uint(0) >> 1)