Skip to content

Commit

Permalink
Merge pull request #47 from ArtisanCloud/develop
Browse files Browse the repository at this point in the history
feature(coroutine): add mutex status checker
  • Loading branch information
Matrix-X authored Sep 7, 2022
2 parents 8dbb6fe + 70885ec commit a8dfb2e
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions cache/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package cache
23 changes: 23 additions & 0 deletions corountine/locker/mutex.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package locker

import (
"reflect"
"sync"
)

const mutexLocked = 1

func MutexLocked(m *sync.Mutex) bool {
state := reflect.ValueOf(m).Elem().FieldByName("state")
return state.Int()&mutexLocked == mutexLocked
}

func RWMutexWriteLocked(rw *sync.RWMutex) bool {
// RWMutex has a "w" sync.Mutex field for write lock
state := reflect.ValueOf(rw).Elem().FieldByName("w").FieldByName("state")
return state.Int()&mutexLocked == mutexLocked
}

func RWMutexReadLocked(rw *sync.RWMutex) bool {
return reflect.ValueOf(rw).Elem().FieldByName("readerCount").Int() > 0
}
37 changes: 37 additions & 0 deletions corountine/locker/mutex_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package locker

import (
"fmt"
"sync"
"testing"
)

func Test_MutexLocked(t *testing.T) {

m := sync.Mutex{}
fmt.Println("m locked =", MutexLocked(&m))
m.Lock()
fmt.Println("m locked =", MutexLocked(&m))
m.Unlock()
fmt.Println("m locked =", MutexLocked(&m))

}

func Test_RWMutexWriteAndReadLocked(t *testing.T) {

rw := sync.RWMutex{}
fmt.Println("rw write locked =", RWMutexWriteLocked(&rw), " read locked =", RWMutexReadLocked(&rw))
rw.Lock()
fmt.Println("rw write locked =", RWMutexWriteLocked(&rw), " read locked =", RWMutexReadLocked(&rw))
rw.Unlock()
fmt.Println("rw write locked =", RWMutexWriteLocked(&rw), " read locked =", RWMutexReadLocked(&rw))
rw.RLock()
fmt.Println("rw write locked =", RWMutexWriteLocked(&rw), " read locked =", RWMutexReadLocked(&rw))
rw.RLock()
fmt.Println("rw write locked =", RWMutexWriteLocked(&rw), " read locked =", RWMutexReadLocked(&rw))
rw.RUnlock()
fmt.Println("rw write locked =", RWMutexWriteLocked(&rw), " read locked =", RWMutexReadLocked(&rw))
rw.RUnlock()
fmt.Println("rw write locked =", RWMutexWriteLocked(&rw), " read locked =", RWMutexReadLocked(&rw))

}

0 comments on commit a8dfb2e

Please sign in to comment.