github.com/leslie-fei/fastcache@v0.0.0-20240520092641-b7a9eb05711f/locker.go (about)

     1  package fastcache
     2  
     3  import (
     4  	"runtime"
     5  	"sync"
     6  	"sync/atomic"
     7  )
     8  
     9  type Locker interface {
    10  	sync.Locker
    11  	RLock()
    12  	RUnlock()
    13  	Reset()
    14  }
    15  
    16  type threadLocker struct {
    17  	sync.RWMutex
    18  }
    19  
    20  //func (l *threadLocker) Lock() {
    21  //
    22  //}
    23  //
    24  //func (l *threadLocker) Unlock() {
    25  //}
    26  
    27  func (l *threadLocker) Reset() {
    28  	// ignore
    29  }
    30  
    31  type processLocker struct {
    32  	write    *int32
    33  	read     *int32
    34  	filepath string // file lock
    35  }
    36  
    37  func (l *processLocker) Lock() {
    38  	// TODO lock timeout
    39  	for !atomic.CompareAndSwapInt32(l.write, 0, 1) {
    40  		runtime.Gosched()
    41  	}
    42  }
    43  
    44  func (l *processLocker) Unlock() {
    45  	if !atomic.CompareAndSwapInt32(l.write, 1, 0) {
    46  		panic("unlock an unlocked-lock")
    47  	}
    48  }
    49  
    50  func (l *processLocker) RLock() {
    51  	// TODO read lock
    52  	l.Lock()
    53  }
    54  
    55  func (l *processLocker) RUnlock() {
    56  	l.Unlock()
    57  }
    58  
    59  func (l *processLocker) Reset() {
    60  	*l.write = 0
    61  }
    62  
    63  var nopLocker = &nonLocker{}
    64  
    65  type nonLocker struct {
    66  }
    67  
    68  func (n *nonLocker) Lock() {
    69  }
    70  
    71  func (n *nonLocker) Unlock() {
    72  }
    73  
    74  func (n *nonLocker) RLock() {
    75  }
    76  
    77  func (n *nonLocker) RUnlock() {
    78  }
    79  
    80  func (n *nonLocker) Reset() {
    81  }