使用方式

    接口文档

    https://pkg.go.dev/github.com/gogf/gf/v2/os/gmlock

    1. func Lock(key string)
    2. func LockFunc(key string, f func())
    3. func RLock(key string)
    4. func RLockFunc(key string, f func())
    5. func RUnlock(key string)
    6. func Remove(key string)
    7. func TryLock(key string) bool
    8. func TryLockFunc(key string, f func()) bool
    9. func TryRLock(key string) bool
    10. func TryRLockFunc(key string, f func()) bool
    11. func Unlock(key string)
    12. type Locker
    13. func New() *Locker
    14. func (l *Locker) Lock(key string)
    15. func (l *Locker) RLock(key string)
    16. func (l *Locker) RLockFunc(key string, f func())
    17. func (l *Locker) RUnlock(key string)
    18. func (l *Locker) Remove(key string)
    19. func (l *Locker) TryLock(key string) bool
    20. func (l *Locker) TryLockFunc(key string, f func()) bool
    21. func (l *Locker) TryRLock(key string) bool
    22. func (l *Locker) TryRLockFunc(key string, f func()) bool
    23. func (l *Locker) Unlock(key string)

    执行后,输出结果为:

    1. 2018-10-15 23:57:28.295 9
    2. 2018-10-15 23:57:29.296 0
    3. 2018-10-15 23:57:30.296 1
    4. 2018-10-15 23:57:32.296 3
    5. 2018-10-15 23:57:34.297 5
    6. 2018-10-15 23:57:35.297 6
    7. 2018-10-15 23:57:36.298 7
    8. 2018-10-15 23:57:37.298 8

    示例2,TryLock非阻塞锁

    TryLock方法是有返回值的,它表示用来尝试获取锁,如果获取成功,则返回true;如果获取失败(即互斥锁已被其他goroutine获取),则返回false

    执行后,输出结果为:

    1. 2018-10-16 00:01:59.172 9
    2. 2018-10-16 00:01:59.172 false
    3. 2018-10-16 00:01:59.172 false
    4. 2018-10-16 00:01:59.172 false
    5. 2018-10-16 00:01:59.172 false
    6. 2018-10-16 00:01:59.172 false
    7. 2018-10-16 00:01:59.172 false
    8. 2018-10-16 00:01:59.172 false
    9. 2018-10-16 00:01:59.176 false