github.com/XiaoMi/Gaea@v1.2.5/util/sync2/semaphore.go (about) 1 /* 2 Copyright 2017 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package sync2 18 19 // What's in a name? Channels have all you need to emulate a counting 20 // semaphore with a boatload of extra functionality. However, in some 21 // cases, you just want a familiar API. 22 23 import ( 24 "time" 25 ) 26 27 // Semaphore is a counting semaphore with the option to 28 // specify a timeout. 29 type Semaphore struct { 30 slots chan struct{} 31 timeout time.Duration 32 } 33 34 // NewSemaphore creates a Semaphore. The count parameter must be a positive 35 // number. A timeout of zero means that there is no timeout. 36 func NewSemaphore(count int, timeout time.Duration) *Semaphore { 37 sem := &Semaphore{ 38 slots: make(chan struct{}, count), 39 timeout: timeout, 40 } 41 for i := 0; i < count; i++ { 42 sem.slots <- struct{}{} 43 } 44 return sem 45 } 46 47 // Acquire returns true on successful acquisition, and 48 // false on a timeout. 49 func (sem *Semaphore) Acquire() bool { 50 if sem.timeout == 0 { 51 <-sem.slots 52 return true 53 } 54 tm := time.NewTimer(sem.timeout) 55 defer tm.Stop() 56 select { 57 case <-sem.slots: 58 return true 59 case <-tm.C: 60 return false 61 } 62 } 63 64 // TryAcquire acquires a semaphore if it's immediately available. 65 // It returns false otherwise. 66 func (sem *Semaphore) TryAcquire() bool { 67 select { 68 case <-sem.slots: 69 return true 70 default: 71 return false 72 } 73 } 74 75 // Release releases the acquired semaphore. You must 76 // not release more than the number of semaphores you've 77 // acquired. 78 func (sem *Semaphore) Release() { 79 sem.slots <- struct{}{} 80 } 81 82 // Size returns the current number of available slots. 83 func (sem *Semaphore) Size() int { 84 return len(sem.slots) 85 }