Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

单例模式导致两个同名mutex并发执行时会死锁 #2

Open
pkufranky opened this issue May 24, 2021 · 0 comments
Open

单例模式导致两个同名mutex并发执行时会死锁 #2

pkufranky opened this issue May 24, 2021 · 0 comments

Comments

@pkufranky
Copy link

pkufranky commented May 24, 2021

两个goroutine并发执行(Lock, do somthing, UnLock),使用NewMutex(name), 传入的是相同的name,因此获取的是同一个mutex

假设routine1先成功获取了redis锁,但在UnLock之前,routine2尝试Lock,就可以看到下面的死锁,都在等待localMtx的释放。
似乎单例模式没啥必要?既然名字叫NewMutex,每次返回新的就可以了

routine 1

Lock1 // 执行成功
do1 // 执行成功
UnLock1 // Lock2已经持有了内部锁localMtx,等待localMtx释放

routine 2
Lock2 // 因为routine1先获取到了redis锁,所以等待在Lock的itn.locker.lock()那行,持有了localMtx锁

func (itn *internal) Lock() {
itn.localMtx.Lock()
itn.locker.lock()
itn.localMtx.Unlock()
}

func (itn *internal) Unlock() {
itn.localMtx.Lock()
itn.locker.unlock()
itn.localMtx.Unlock()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant