github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/spinlock.go (about)

     1  package utils
     2  
     3  import (
     4  	"runtime"
     5  	"sync"
     6  	"sync/atomic"
     7  )
     8  
     9  /*
    10     Creation Time: 2021 - Jan - 01
    11     Created by:  (ehsan)
    12     Maintainers:
    13        1.  Ehsan N. Moosa (E2)
    14     Auditor: Ehsan N. Moosa (E2)
    15  */
    16  
    17  // SpinLock is a spinlock implementation.
    18  //
    19  // A SpinLock must not be copied after first use.
    20  // This SpinLock intended to be used to synchronize exceptionally short-lived operations.
    21  type SpinLock struct {
    22  	lock uintptr
    23  	_    sync.Mutex // for copy protection compiler warning
    24  }
    25  
    26  // Lock locks l.
    27  // If the lock is already in use, the calling goroutine
    28  // blocks until the locker is available.
    29  func (l *SpinLock) Lock() {
    30  	for !atomic.CompareAndSwapUintptr(&l.lock, 0, 1) {
    31  		runtime.Gosched()
    32  	}
    33  }
    34  
    35  // Unlock unlocks l.
    36  func (l *SpinLock) Unlock() {
    37  	atomic.StoreUintptr(&l.lock, 0)
    38  }