Skip to content

Instantly share code, notes, and snippets.

@chenminhua
Created May 15, 2018 05:02
Show Gist options
  • Save chenminhua/2a5b9823833b7f96084bf4993a32081c to your computer and use it in GitHub Desktop.
Save chenminhua/2a5b9823833b7f96084bf4993a32081c to your computer and use it in GitHub Desktop.
基于etcd的分布式锁
func main() {
c, err := clientv3.New(clientv3.Config{
Endpoints: []string{"ip:port"},
DialTimeout: 5 * time.Second,
})
if err != nil {
panic(err)
}
lockKey := "/lock"
session, err := concurrency.NewSession(c)
if err != nil {
panic(err)
}
fmt.Println("locking")
m := concurrency.NewMutex(session, lockKey)
if err := m.Lock(context.TODO()); err != nil {
panic(err)
}
fmt.Println(m)
time.Sleep(2000000000)
fmt.Println("unlocking")
m.Unlock(context.TODO())
}
@Xiaocge
Copy link

Xiaocge commented Jul 26, 2022

想问下, 现在clientv3 如果 time.Sleep(2000000000) 换成业务代码 , 中间执行失败了. 导致 m.Unlock(context.TODO()) 没有执行. 这个锁 还会自动释放吗?

@chenminhua
Copy link
Author

想问下, 现在clientv3 如果 time.Sleep(2000000000) 换成业务代码 , 中间执行失败了. 导致 m.Unlock(context.TODO()) 没有执行. 这个锁 还会自动释放吗?

这个取决于业务代码执行失败后是怎么处理的,是Log error?Return early?还是直接panic?

但是没错,这个代码并不鲁棒,当时只是为了测试一下etcd。应该在Lock后立即 defer UnLock。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment