github.com/uber/kraken@v0.1.4/utils/syncutil/counters.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package syncutil 15 16 import "sync" 17 18 // counter is an element in a Counters struct, wrapping a count and its lock. 19 type counter struct { 20 mu sync.RWMutex 21 count int 22 } 23 24 // Counters provides a wrapper to a list of counters that supports 25 // concurrent update-only operations. 26 type Counters []counter 27 28 // NewCounters returns an initialized Counters of the given length. 29 func NewCounters(length int) Counters { 30 return Counters(make([]counter, length)) 31 } 32 33 // Len returns the number of counters in the Counters. 34 func (c Counters) Len() int { 35 return len(c) 36 } 37 38 // Get returns the count of the counter at index i. 39 func (c Counters) Get(i int) int { 40 c[i].mu.RLock() 41 defer c[i].mu.RUnlock() 42 43 return c[i].count 44 } 45 46 // Set sets the count of the counter at index i to count v. 47 func (c Counters) Set(i, v int) { 48 c[i].mu.Lock() 49 defer c[i].mu.Unlock() 50 51 c[i].count = v 52 } 53 54 // Increment increments the count of the counter at index i. 55 func (c Counters) Increment(i int) { 56 c[i].mu.Lock() 57 defer c[i].mu.Unlock() 58 59 c[i].count++ 60 } 61 62 // Decrement decrements the count of the counter at index i. 63 func (c Counters) Decrement(i int) { 64 c[i].mu.Lock() 65 defer c[i].mu.Unlock() 66 67 c[i].count-- 68 }