OLD | NEW |
---|---|
1 // Copyright 2015 The Chromium Authors. All rights reserved. | 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 package parallel | 5 package parallel |
6 | 6 |
7 // Semaphore is a sync.Locker that implements a n-semaphore. | 7 // Semaphore is a sync.Locker that implements a n-semaphore. |
8 // | 8 // |
9 // Lock the semaphore acquires a semaphore token, possibly blocking until one | 9 // Lock the semaphore acquires a semaphore token, possibly blocking until one |
10 // is available. | 10 // is available. |
11 // | 11 // |
12 // Unlock releases an owned token, returning it to the semaphore. | 12 // Unlock releases an owned token, returning it to the semaphore. |
13 type Semaphore chan struct{} | 13 type Semaphore chan struct{} |
14 | 14 |
15 // Lock acquires a semaphore resource, blocking until one is available. | 15 // Lock acquires a semaphore resource, blocking until one is available. |
16 func (s Semaphore) Lock() { | 16 func (s Semaphore) Lock() { |
17 if cap(s) > 0 { | 17 if cap(s) > 0 { |
18 s <- struct{}{} | 18 s <- struct{}{} |
19 } | 19 } |
20 } | 20 } |
21 | 21 |
22 // Unlock releases a single semaphore resource. | 22 // Unlock releases a single semaphore resource. |
23 func (s Semaphore) Unlock() { | 23 func (s Semaphore) Unlock() { |
24 if cap(s) > 0 { | 24 if cap(s) > 0 { |
25 <-s | 25 <-s |
26 } | 26 } |
27 } | 27 } |
28 | |
29 // TakeAll blocks until it holds all available semaphore resources. When it | |
30 // returns, the caller owns all of the resources in the semaphore. | |
31 func (s Semaphore) TakeAll() { | |
dnj (Google)
2016/02/10 03:19:04
This is really useful. Before, one would have to u
| |
32 for i := 0; i < cap(s); i++ { | |
33 s.Lock() | |
34 } | |
35 } | |
OLD | NEW |