gf/g/os/gmlock/gmlock.go

74 lines
2.2 KiB
Go
Raw Normal View History

// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2019-01-15 23:27:47 +08:00
// Package gmlock implements a thread-safe memory locker.
package gmlock
import "time"
var (
locker = New()
)
2019-06-05 21:58:27 +08:00
// TryLock tries locking the <key> with write lock,
// it returns true if success, or if there's a write/read lock the <key>,
// it returns false. The parameter <expire> specifies the max duration it locks.
func TryLock(key string, expire...time.Duration) bool {
return locker.TryLock(key, expire...)
}
2019-06-05 21:58:27 +08:00
// Lock locks the <key> with write lock.
// If there's a write/read lock the <key>,
// it will blocks until the lock is released.
// The parameter <expire> specifies the max duration it locks.
func Lock(key string, expire...time.Duration) {
locker.Lock(key, expire...)
}
2019-06-05 21:58:27 +08:00
// Unlock unlocks the write lock of the <key>.
func Unlock(key string) {
locker.Unlock(key)
}
2019-06-05 21:58:27 +08:00
// TryRLock tries locking the <key> with read lock.
// It returns true if success, or if there's a write lock on <key>, it returns false.
func TryRLock(key string) bool {
return locker.TryRLock(key)
}
2019-06-05 21:58:27 +08:00
// RLock locks the <key> with read lock.
// If there's a write lock on <key>,
// it will blocks until the write lock is released.
func RLock(key string) {
locker.RLock(key)
}
2019-06-05 21:58:27 +08:00
// RUnlock unlocks the read lock of the <key>.
func RUnlock(key string) {
locker.RUnlock(key)
}
2019-06-05 21:58:27 +08:00
// LockFunc locks the <key> with write lock and callback function <f>.
// If there's a write/read lock the <key>,
// it will blocks until the lock is released.
//
// It releases the lock after <f> is executed.
//
// The parameter <expire> specifies the max duration it locks.
func LockFunc(key string, f func(), expire...time.Duration) {
locker.LockFunc(key, f, expire...)
}
2019-06-05 21:58:27 +08:00
// RLockFunc locks the <key> with read lock and callback function <f>.
// If there's a write lock the <key>,
// it will blocks until the lock is released.
//
// It releases the lock after <f> is executed.
//
// The parameter <expire> specifies the max duration it locks.
func RLockFunc(key string, f func()) {
locker.RLockFunc(key, f)
}