diff --git a/cache/cache.go b/cache/cache.go new file mode 100644 index 0000000..08bf029 --- /dev/null +++ b/cache/cache.go @@ -0,0 +1 @@ +package cache diff --git a/corountine/locker/mutex.go b/corountine/locker/mutex.go new file mode 100644 index 0000000..9e833a4 --- /dev/null +++ b/corountine/locker/mutex.go @@ -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 +} diff --git a/corountine/locker/mutex_test.go b/corountine/locker/mutex_test.go new file mode 100644 index 0000000..d05a367 --- /dev/null +++ b/corountine/locker/mutex_test.go @@ -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)) + +}