github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/tools/spinlock.go (about)

     1  package tools
     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     Copyright Ronak Software Group 2020
    16  */
    17  
    18  // SpinLock is a spinlock implementation.
    19  //
    20  // A SpinLock must not be copied after first use.
    21  // This SpinLock intended to be used to synchronize exceptionally short-lived operations.
    22  type SpinLock struct {
    23  	_    sync.Mutex // for copy protection compiler warning
    24  	lock uintptr
    25  }
    26  
    27  // Lock locks l.
    28  // If the lock is already in use, the calling goroutine
    29  // blocks until the locker is available.
    30  func (l *SpinLock) Lock() {
    31  	for !atomic.CompareAndSwapUintptr(&l.lock, 0, 1) {
    32  		runtime.Gosched()
    33  	}
    34  }
    35  
    36  // Unlock unlocks l.
    37  func (l *SpinLock) Unlock() {
    38  	atomic.StoreUintptr(&l.lock, 0)
    39  }