Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upsync: add Mutex.MustBeLocked #1366
Comments
It seems like a useful debugging tool, but I'm also a little horrified by the idea of code complex enough to need it. As you observed, the IsUnlocked described here isn't reliable - an AssertUnlocked that panics if the mutex is locked would be better. Labels changed: added packagechange. Owner changed to r...@golang.org. Status changed to Thinking. |
|
Comment 3 by cw@f00f.org: Why not an atomic LockIfUnlocked? That's useful sometimes to grab a lock when it's unlocked and fail otherwise. It's also race free. IsLocked for debugging can be done via other means. |
To prevent careless programming, I want to panic if a lock is not held at a certain point. I could see the rationale for making this panic and renaming the method MustBeLocked() or PanicIfUnlocked(). I can't think of too many valid use cases other than panicking. I can see people not reading it carefully and assuming that !IsUnlocked() means that they hold the lock, or that if IsUnlocked() { Lock() } would only lock if you weren't already. diff -r 23006c94f1aa src/pkg/sync/mutex.go --- a/src/pkg/sync/mutex.go Fri Dec 17 14:00:46 2010 -0800 +++ b/src/pkg/sync/mutex.go Tue Dec 21 15:12:49 2010 -0800 @@ -59,3 +59,13 @@ } runtime.Semrelease(&m.sema) } + +// Check if the mutex lock is unlocked. +// The most common case is where you want to fail code with a high probability +// if a mutex is not locked. There is no false positive, but there is a +// false negative if another goroutine is holding the lock. +func (m *Mutex) IsUnlocked() bool { + return m.key == 0 +} + +