Skip to content

sync: mutex.TryLock #6123

Closed
Closed
@lukescott

Description

@lukescott
This has come up several times on the mailing list. Looking for something like this to
be provided in sync.Mutex:

func (m *Mutex) TryLock() (locked bool) {
    locked = atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked)
    if locked && raceenabled {
        raceAcquire(unsafe.Pointer(m))
    }
    return
}

Now you could use CompareAndSwapInt32 yourself. But it gets tricky when you need to use
Lock in one function, and TryLock in another on the same mutex.

The typical use-case is something like this:

if m.TryLock() {
    // do something
} else {
    // do something else
}

It's very similar to select default for channels:

select {
case <-c:
// do something
default:
// do something else
}

The difference being that with such a function you can do this with a primitive.

Other languages provide this functionality:

Java:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html#tryLock()
Objective-C:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSLock_Class/Reference/Reference.html#//apple_ref/occ/instm/NSLock/tryLock

A "LockBeforeTime" would also be useful, but I understand that's more
difficult to implement.

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