github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/net/internal/spinlock.go (about)

     1  package internal
     2  
     3  import (
     4  	"runtime"
     5  	"sync"
     6  	"sync/atomic"
     7  )
     8  
     9  // this is a good candidate for a lock-free structure.
    10  type spinLock uint32
    11  
    12  func (sl *spinLock) Lock() {
    13  	for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
    14  		runtime.Gosched()
    15  	}
    16  }
    17  
    18  func (sl *spinLock) Unlock() {
    19  	atomic.StoreUint32((*uint32)(sl), 0)
    20  }
    21  
    22  // SpinLock creates a new spin-lock.
    23  func SpinLock() sync.Locker {
    24  	return new(spinLock)
    25  }