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

View File

@ -3,10 +3,9 @@ package net
import (
"net"
"sync"
"sync/atomic"
"unsafe"
"github.com/metacubex/mihomo/common/buf"
"github.com/metacubex/mihomo/common/once"
)
type earlyConn struct {
@ -44,8 +43,7 @@ func (conn *earlyConn) Upstream() any {
}
func (conn *earlyConn) Success() bool {
// atomic visit sync.Once.done
return atomic.LoadUint32((*uint32)(unsafe.Pointer(&conn.resOnce))) == 1 && conn.resErr == nil
return once.Done(&conn.resOnce) && conn.resErr == nil
}
func (conn *earlyConn) ReaderReplaceable() bool {

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)
}

View File

@ -8,6 +8,7 @@ import (
"sync"
"time"
mihomoOnce "github.com/metacubex/mihomo/common/once"
mihomoHttp "github.com/metacubex/mihomo/component/http"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
@ -96,5 +97,5 @@ func DownloadMMDB(path string) (err error) {
}
func Reload() {
once = sync.Once{}
mihomoOnce.Reset(&once)
}