使用方式:
接口文档:
https://pkg.go.dev/github.com/gogf/gf/v2/os/gmlock
func Lock(key string)
func LockFunc(key string, f func())
func RLock(key string)
func RLockFunc(key string, f func())
func RUnlock(key string)
func Remove(key string)
func TryLock(key string) bool
func TryLockFunc(key string, f func()) bool
func TryRLock(key string) bool
func TryRLockFunc(key string, f func()) bool
func Unlock(key string)
type Locker
func New() *Locker
func (l *Locker) Lock(key string)
func (l *Locker) RLock(key string)
func (l *Locker) RLockFunc(key string, f func())
func (l *Locker) RUnlock(key string)
func (l *Locker) Remove(key string)
func (l *Locker) TryLock(key string) bool
func (l *Locker) TryLockFunc(key string, f func()) bool
func (l *Locker) TryRLock(key string) bool
func (l *Locker) TryRLockFunc(key string, f func()) bool
func (l *Locker) Unlock(key string)
执行后,输出结果为:
2018-10-15 23:57:28.295 9
2018-10-15 23:57:29.296 0
2018-10-15 23:57:30.296 1
2018-10-15 23:57:32.296 3
2018-10-15 23:57:34.297 5
2018-10-15 23:57:35.297 6
2018-10-15 23:57:36.298 7
2018-10-15 23:57:37.298 8
示例2,TryLock非阻塞锁
TryLock
方法是有返回值的,它表示用来尝试获取锁,如果获取成功,则返回true
;如果获取失败(即互斥锁已被其他goroutine
获取),则返回false
。
执行后,输出结果为:
2018-10-16 00:01:59.172 9
2018-10-16 00:01:59.172 false
2018-10-16 00:01:59.172 false
2018-10-16 00:01:59.172 false
2018-10-16 00:01:59.172 false
2018-10-16 00:01:59.172 false
2018-10-16 00:01:59.172 false
2018-10-16 00:01:59.172 false
2018-10-16 00:01:59.176 false