github.com/gitbookio/syncgroup@v0.0.0-20181003125046-3e73b2e6a972/mutex.go (about)

     1  package syncgroup
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  )
     7  
     8  // rwmutex is a RWMutex that tracks it's use
     9  // and after each lock/unlock reports it's current usage
    10  type rwmutex struct {
    11  	count counter
    12  	mutex sync.RWMutex
    13  }
    14  
    15  func (rw *rwmutex) RLock() int64 {
    16  	active := rw.count.Inc()
    17  	rw.mutex.RLock()
    18  	return active
    19  }
    20  
    21  func (rw *rwmutex) Lock() int64 {
    22  	count := rw.count.Inc()
    23  	rw.mutex.Lock()
    24  	return count
    25  }
    26  
    27  func (rw *rwmutex) RUnlock() int64 {
    28  	rw.mutex.RUnlock()
    29  	return rw.count.Dec()
    30  }
    31  
    32  func (rw *rwmutex) Unlock() int64 {
    33  	rw.mutex.Unlock()
    34  	return rw.count.Dec()
    35  }
    36  
    37  // counter is a simple atomically safe counter
    38  type counter struct {
    39  	count int64
    40  }
    41  
    42  func (c *counter) Inc() int64 {
    43  	return atomic.AddInt64(&c.count, +1)
    44  }
    45  
    46  func (c *counter) Dec() int64 {
    47  	return atomic.AddInt64(&c.count, -1)
    48  }
    49  
    50  func (c *counter) Get() int64 {
    51  	return atomic.LoadInt64(&c.count)
    52  }