golang实现自旋锁

import (
	"runtime"
	"sync"
	"sync/atomic"
)

type spinLock uint32

var maxBackoff = 64

// Lock 加锁
func (sl *spinLock)Lock(){
	backoff := 1
	for{
		for i := 0; i < backoff; i++{
			if !atomic.CompareAndSwapUint32((*uint32)(sl),0,1){	//加锁失败,让出cpu调度
				runtime.Gosched()
			}
			if backoff < maxBackoff{
				backoff = backoff << 1
			}
		}
	}
}

// Unlock 释放锁
func (sl *spinLock)Unlock(){
	atomic.StoreUint32((*uint32)(sl), 1)
}


// NewSpinLock 创建自旋锁对象
func NewSpinLock()sync.Locker{
	return new(spinLock)


你可能感兴趣的:(golang,开发语言,后端)