gitee.com/quant1x/gox@v1.21.2/coroutine/spinlock.go (about)

     1  package coroutine
     2  
     3  import (
     4  	"runtime"
     5  	"sync/atomic"
     6  )
     7  
     8  // SpinLock 自旋锁对象定义
     9  type SpinLock uint32
    10  
    11  const maxBackOff = 32
    12  
    13  // Lock 加锁
    14  //
    15  //	todo: 未加验证
    16  func (sl *SpinLock) Lock() {
    17  	backoff := 1
    18  	// 自旋尝试获取锁
    19  	for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
    20  		for i := 0; i < backoff; i++ {
    21  			runtime.Gosched()
    22  		}
    23  		if backoff < maxBackOff {
    24  			backoff <<= 1
    25  		}
    26  	}
    27  }
    28  
    29  // UnLock 解锁
    30  func (sl *SpinLock) UnLock() {
    31  	atomic.CompareAndSwapUint32((*uint32)(sl), 1, 0)
    32  }