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

proposal: sync: Add IsLocked() to avoid dead lock or unlock a unlocked lock. #56829

Closed
MeteorsLiu opened this issue Nov 18, 2022 · 4 comments
Closed

Comments

@MeteorsLiu
Copy link

Some time, if a developer forgot to unlock and try to lock the Mutex, it will cause dead lock.

And go 1.18 add TryLock().

But this is no for Unlock().

Still, if if a developer forgot to lock and try to unlock the Mutex, it will panic.

Why not add a IsLocked().

var lock sync.Mutex
if lock.IsLocked() {
lock.Unlock()
}
@gopherbot gopherbot added this to the Proposal milestone Nov 18, 2022
@ianlancetaylor
Copy link
Contributor

I don't see how this can be used safely by multiple goroutines. TryLock is safe because if it succeeds it locks the mutex. But in your example in between IsLocked returning and the call to Unlock some other goroutine may call Unlock.

@MeteorsLiu
Copy link
Author

MeteorsLiu commented Nov 18, 2022

I don't see how this can be used safely by multiple goroutines. TryLock is safe because if it succeeds it locks the mutex. But in your example in between IsLocked returning and the call to Unlock some other goroutine may call Unlock.

Maybe add TryUnlock?

I think it's possible.

IsLocked use atomic.Load to check whether it's locked.

If it's locked, try unlock or avoid locking it again.

@thediveo
Copy link

What actually would be the use case for attempted unlocking? I'm wondering what this could be but have no idea where this is needed not just because the underlying code is fundamentally broken?

@seankhliao
Copy link
Member

Locks are typically used to ensure exclusive access to some resource.
The need for something like IsLocked or TryUnlock would indicate that the code at that point does not know if it's locked, which runs counter to proper use of locks, and that exclusivity isn't being preserved.

@golang golang locked and limited conversation to collaborators Nov 19, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants