Skip to content

sync: add Mutex.MustBeLocked #1366

@msolo

Description

@msolo
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
+}
+
+

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions