diff --git a/g/os/gcache/gcache.go b/g/os/gcache/gcache.go index 38eddad6b..ad0ae5a40 100644 --- a/g/os/gcache/gcache.go +++ b/g/os/gcache/gcache.go @@ -96,6 +96,20 @@ func BatchRemove(keys []string) { cache.BatchRemove(keys) } +// 基于内存缓存的锁,锁成功返回true,失败返回false,当失败时表示有其他的锁存在 +func Lock(key string, expire int64) bool { + if v := cache.Get(key); v != nil { + return false + } + cache.Set(key, struct {}{}, expire) + return true +} + +// 解除基于内存缓存的锁 +func Unlock(key string) { + cache.Remove(key) +} + // 获得所有的键名,组成字符串数组返回 func Keys() []string { return cache.Keys() @@ -175,6 +189,20 @@ func (c *Cache) BatchSet(data map[string]interface{}, expire int64) { } } +// 基于内存缓存的锁,锁成功返回true,失败返回false,当失败时表示有其他的锁存在 +func (c *Cache) Lock(key string, expire int64) bool { + if v := c.Get(key); v != nil { + return false + } + c.Set(key, struct {}{}, expire) + return true +} + +// 解除基于内存缓存的锁 +func (c *Cache) Unlock(key string) { + c.Remove(key) +} + // 获取指定键名的值 func (c *Cache) Get(key string) interface{} { c.dmu.RLock()