Redis分布式锁——关于睡眠时间问题

1. 运行环境

Redis分布式锁——关于睡眠时间问题

Redis分布式锁——关于睡眠时间问题

2. 问题描述?

gitlab的项目:github.com/go-redsync/redsync
为什么time.sleep设置4秒可以,但是5秒就死锁了
Redis分布式锁——关于睡眠时间问题

Redis分布式锁——关于睡眠时间问题

func main() {
    // Create a pool with go-redis (or redigo) which is the pool redisync will
    // use while communicating with Redis. This can also be any pool that
    // implements the `redis.Pool` interface.
    client := goredislib.NewClient(&goredislib.Options{
        Addr: "xxxx.xxxx.xxxx.xxxx:6379",
    })
    pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)

    // Create an instance of redisync to be used to obtain a mutual exclusion
    // lock.
    rs := redsync.New(pool)

    // Obtain a new mutex by using the same name for all instances wanting the
    // same lock.

    mutexname := "421"
    gNum := 2
    var wg sync.WaitGroup
    wg.Add(gNum)
    for i := 0; i < gNum; i++ {
        go func() {
            defer wg.Done()
            mutex := rs.NewMutex(mutexname)
            fmt.Println("开始获取锁")
            if err := mutex.Lock(); err != nil {
                panic(err)
            }
            fmt.Println("获取锁成功")
            time.Sleep(time.Second * 4)
            fmt.Println("开始释放锁")
            if ok, err := mutex.Unlock(); !ok || err != nil {
                panic("unlock failed")
            }
            fmt.Println("释放锁成功")
        }()
    }
    wg.Wait()

}

3. 您期望得到的结果?

time.sleep设置4秒可以,但是5秒就死锁的原因

4. 您实际得到的结果?

panic: lock already taken, locked nodes: [0]

讨论数量: 2
ctx, cancel := context.WithTimeout(ctx, time.Duration(int64(float64(m.expiry)*m.timeoutFactor)))
            defer cancel()
            return m.actOnPoolsAsync(func(pool redis.Pool) (bool, error) {
                return m.release(ctx, pool, value)
            })

这里 expiry = 8 , timeoutFactor=0.5 所以4s超时

2天前 评论
weekong (楼主) 1天前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!