From 5888b0e06aabb6f9584cdb8716f18e30d0b248cb Mon Sep 17 00:00:00 2001 From: john Date: Tue, 18 Jun 2019 19:19:43 +0800 Subject: [PATCH] fix issue in gmlock --- g/os/glog/glog_logger.go | 5 +++++ g/os/gmlock/gmlock_mutex.go | 11 ++++++----- g/test/gtest/gtest.go | 7 ++++++- geg/other/test2.go | 10 ++++++---- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/g/os/glog/glog_logger.go b/g/os/glog/glog_logger.go index 5d6562d98..064e31ddc 100644 --- a/g/os/glog/glog_logger.go +++ b/g/os/glog/glog_logger.go @@ -17,6 +17,7 @@ import ( "github.com/gogf/gf/g/util/gconv" "io" "os" + "regexp" "runtime" "strings" "time" @@ -356,6 +357,10 @@ func (l *Logger) GetBacktrace(skip...int) string { // Find the true caller file path using custom skip. index := 1 goRoot := runtime.GOROOT() + if goRoot != "" { + goRoot = strings.ReplaceAll(goRoot, "\\", "/") + goRoot = regexp.QuoteMeta(goRoot) + } for i := from + customSkip + l.btSkip; i < 1000; i++ { if _, file, cline, ok := runtime.Caller(i); ok && len(file) > 2 { if (goRoot == "" || !gregex.IsMatchString("^" + goRoot, file)) && !gregex.IsMatchString(``, file) { diff --git a/g/os/gmlock/gmlock_mutex.go b/g/os/gmlock/gmlock_mutex.go index 6c345508f..425c49d2c 100644 --- a/g/os/gmlock/gmlock_mutex.go +++ b/g/os/gmlock/gmlock_mutex.go @@ -63,12 +63,13 @@ func (m *Mutex) Unlock() { // it returns false. func (m *Mutex) TryLock() bool { if m.locking.Cas(false, true) { - m.mu.Lock() - // State should be changed after locks. - m.state.Set(-1) - m.wid.Add(1) + if m.state.Cas(0, -1) { + m.mu.Lock() + m.wid.Add(1) + m.locking.Set(false) + return true + } m.locking.Set(false) - return true } return false } diff --git a/g/test/gtest/gtest.go b/g/test/gtest/gtest.go index 9c3adc920..b4d229d90 100644 --- a/g/test/gtest/gtest.go +++ b/g/test/gtest/gtest.go @@ -14,6 +14,7 @@ import ( "reflect" "regexp" "runtime" + "strings" "testing" ) @@ -315,8 +316,12 @@ func getBacktrace(skip...int) string { } } } - // Get the caller backtrace from business caller file. + // Converting all file separator to "/". goRoot := runtime.GOROOT() + if goRoot != "" { + goRoot = strings.ReplaceAll(goRoot, "\\", "/") + goRoot = regexp.QuoteMeta(goRoot) + } for i := from + customSkip; i < 10000; i++ { if _, file, cline, ok := runtime.Caller(i); ok && file != "" { if reg, _ := regexp.Compile(``); reg.MatchString(file) { diff --git a/geg/other/test2.go b/geg/other/test2.go index 3b6ef239b..45e8670ab 100644 --- a/geg/other/test2.go +++ b/geg/other/test2.go @@ -2,11 +2,13 @@ package main import ( "fmt" - "sync" + "github.com/gogf/gf/g/os/gmlock" + "time" ) func main() { - m := sync.RWMutex{} - m.Lock() - fmt.Println(m) + key := "test3" + gmlock.Lock(key, 200*time.Millisecond) + fmt.Println("TryLock:", gmlock.TryLock(key)) + fmt.Println("TryLock:", gmlock.TryLock(key)) }