From 974332c0ccd64fde54e7714c093b2d40b6b982ef Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Tue, 5 Mar 2024 10:57:25 +0800 Subject: [PATCH] chore: rebuild sync.Once visit code --- common/net/earlyconn.go | 6 ++---- common/once/once_go120.go | 26 ++++++++++++++++++++++++++ common/once/once_go122.go | 26 ++++++++++++++++++++++++++ component/mmdb/mmdb.go | 3 ++- 4 files changed, 56 insertions(+), 5 deletions(-) create mode 100644 common/once/once_go120.go create mode 100644 common/once/once_go122.go diff --git a/common/net/earlyconn.go b/common/net/earlyconn.go index c9a428194..82d392eeb 100644 --- a/common/net/earlyconn.go +++ b/common/net/earlyconn.go @@ -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 { diff --git a/common/once/once_go120.go b/common/once/once_go120.go new file mode 100644 index 000000000..51578a2da --- /dev/null +++ b/common/once/once_go120.go @@ -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) +} diff --git a/common/once/once_go122.go b/common/once/once_go122.go new file mode 100644 index 000000000..5ff8461d6 --- /dev/null +++ b/common/once/once_go122.go @@ -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) +} diff --git a/component/mmdb/mmdb.go b/component/mmdb/mmdb.go index 24edb5e52..66b632beb 100644 --- a/component/mmdb/mmdb.go +++ b/component/mmdb/mmdb.go @@ -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) }