2024-04-06 22:43:36 +08:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2024-10-19 07:04:21 +08:00
|
|
|
"time"
|
2024-04-06 22:43:36 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var GlobalCacheLocks = NewCacheLocks()
|
|
|
|
|
|
|
|
type CacheLocks struct {
|
2024-06-25 21:27:44 +08:00
|
|
|
locks map[uint32]*sync.Mutex
|
2024-04-06 22:43:36 +08:00
|
|
|
mutex sync.Mutex // Protects the 'locks' map
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCacheLocks() *CacheLocks {
|
|
|
|
return &CacheLocks{
|
2024-06-25 21:27:44 +08:00
|
|
|
locks: make(map[uint32]*sync.Mutex),
|
2024-04-06 22:43:36 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-25 21:27:44 +08:00
|
|
|
func (c *CacheLocks) Lock(id uint32) {
|
2024-04-06 22:43:36 +08:00
|
|
|
c.mutex.Lock()
|
|
|
|
if _, exists := c.locks[id]; !exists {
|
|
|
|
c.locks[id] = &sync.Mutex{}
|
|
|
|
}
|
|
|
|
mtx := c.locks[id]
|
|
|
|
c.mutex.Unlock()
|
|
|
|
|
|
|
|
mtx.Lock() // Lock the specific ID mutex
|
|
|
|
}
|
|
|
|
|
2024-06-25 21:27:44 +08:00
|
|
|
func (c *CacheLocks) Unlock(id uint32) {
|
2024-04-06 22:43:36 +08:00
|
|
|
c.mutex.Lock()
|
|
|
|
if mtx, exists := c.locks[id]; exists {
|
|
|
|
mtx.Unlock()
|
2024-10-19 07:04:21 +08:00
|
|
|
go c.RemoveLockId(id, 30)
|
|
|
|
}
|
|
|
|
c.mutex.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *CacheLocks) RemoveLockId(id uint32, delayInSecs time.Duration) {
|
|
|
|
time.Sleep(delayInSecs * time.Second)
|
|
|
|
|
|
|
|
c.mutex.Lock()
|
|
|
|
if _, exists := c.locks[id]; exists {
|
|
|
|
delete(c.locks, id)
|
2024-04-06 22:43:36 +08:00
|
|
|
}
|
|
|
|
c.mutex.Unlock()
|
|
|
|
}
|