github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/sync2/spin.go (about)

     1  package sync2
     2  
     3  import (
     4  	"runtime"
     5  	"sync/atomic"
     6  )
     7  
     8  type SpinMutex struct {
     9  	locked int64
    10  	_      [7]int64
    11  }
    12  
    13  func (m *SpinMutex) Lock() {
    14  	for atomic.SwapInt64(&m.locked, 1) == 1 {
    15  		for try := 0; atomic.LoadInt64(&m.locked) == 1; try++ {
    16  			if try > 256 {
    17  				runtime.Gosched()
    18  			}
    19  		}
    20  	}
    21  }
    22  func (m *SpinMutex) Unlock() {
    23  	atomic.StoreInt64(&m.locked, 0)
    24  }