chore: rebuild sync.Once visit code

This commit is contained in:
wwqgtxx
2024-03-05 10:57:25 +08:00
parent 8b9813079b
commit 974332c0cc
4 changed files with 56 additions and 5 deletions

26
common/once/once_go120.go Normal file
View File

@@ -0,0 +1,26 @@
//go:build !go1.22
package once
import (
"sync"
"sync/atomic"
"unsafe"
)
type Once struct {
done uint32
m sync.Mutex
}
func Done(once *sync.Once) bool {
// atomic visit sync.Once.done
return atomic.LoadUint32((*uint32)(unsafe.Pointer(once))) == 1
}
func Reset(once *sync.Once) {
o := (*Once)(unsafe.Pointer(once))
o.m.Lock()
defer o.m.Unlock()
atomic.StoreUint32(&o.done, 0)
}

26
common/once/once_go122.go Normal file
View File

@@ -0,0 +1,26 @@
//go:build go1.22
package once
import (
"sync"
"sync/atomic"
"unsafe"
)
type Once struct {
done atomic.Uint32
m sync.Mutex
}
func Done(once *sync.Once) bool {
// atomic visit sync.Once.done
return (*atomic.Uint32)(unsafe.Pointer(once)).Load() == 1
}
func Reset(once *sync.Once) {
o := (*Once)(unsafe.Pointer(once))
o.m.Lock()
defer o.m.Unlock()
o.done.Store(0)
}