2 Star 2 Fork 7

王布衣 / gox

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
spinlock.go 515 Bytes
Copy Edit Raw Blame History
王布衣 authored 2023-12-03 18:53 . 增加自旋锁
package coroutine
import (
"runtime"
"sync/atomic"
)
// SpinLock 自旋锁对象定义
type SpinLock uint32
const maxBackOff = 32
// Lock 加锁
//
// todo: 未加验证
func (sl *SpinLock) Lock() {
backoff := 1
// 自旋尝试获取锁
for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
for i := 0; i < backoff; i++ {
runtime.Gosched()
}
if backoff < maxBackOff {
backoff <<= 1
}
}
}
// UnLock 解锁
func (sl *SpinLock) UnLock() {
atomic.CompareAndSwapUint32((*uint32)(sl), 1, 0)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.21.2

Search

344bd9b3 5694891 D2dac590 5694891