Redis分布式锁——关于睡眠时间问题 
                            
                                                    
                        
                    
                    
  
                    
                    1. 运行环境


2. 问题描述?
gitlab的项目:github.com/go-redsync/redsync
为什么time.sleep设置4秒可以,但是5秒就死锁了

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]
          
          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: