github.com/GoWebProd/gip@v0.0.0-20230623090727-b60d41d5d320/spinlock/spinlock.go (about)

     1  package spinlock
     2  
     3  import (
     4  	"runtime"
     5  	"sync/atomic"
     6  )
     7  
     8  type noCopy struct{}
     9  
    10  // Locker is a spinlock implementation.
    11  //
    12  // A Locker must not be copied after first use.
    13  type Locker struct {
    14  	noCopy noCopy
    15  
    16  	lock uintptr
    17  }
    18  
    19  // Lock locks l.
    20  // If the lock is already in use, the calling goroutine
    21  // blocks until the locker is available.
    22  //go:nosplit
    23  func (l *Locker) Lock() {
    24  	for !atomic.CompareAndSwapUintptr(&l.lock, 0, 1) {
    25  		runtime.Gosched()
    26  	}
    27  }
    28  
    29  // Unlock unlocks l.
    30  //go:nosplit
    31  func (l *Locker) Unlock() {
    32  	atomic.StoreUintptr(&l.lock, 0)
    33  }