Skip to content

Instantly share code, notes, and snippets.

@smallnest
Created March 19, 2018 11:30
Show Gist options
  • Save smallnest/d9d98e04795bf52efe3087afd98c4197 to your computer and use it in GitHub Desktop.
Save smallnest/d9d98e04795bf52efe3087afd98c4197 to your computer and use it in GitHub Desktop.
package trylock
import (
"sync"
"sync/atomic"
"unsafe"
)
const mutexLocked = 1 << iota
// Mutex is simple sync.Mutex + ability to try to Lock.
type Mutex struct {
in sync.Mutex
}
// Lock locks m.
// If the lock is already in use, the calling goroutine
// blocks until the mutex is available.
func (m *Mutex) Lock() {
m.in.Lock()
}
// Unlock unlocks m.
// It is a run-time error if m is not locked on entry to Unlock.
//
// A locked Mutex is not associated with a particular goroutine.
// It is allowed for one goroutine to lock a Mutex and then
// arrange for another goroutine to unlock it.
func (m *Mutex) Unlock() {
m.in.Unlock()
}
// TryLock tries to lock m. It returns true in case of success, false otherwise.
func (m *Mutex) TryLock() bool {
return atomic.CompareAndSwapInt32((*int32)(unsafe.Pointer(&m.in)), 0, mutexLocked)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment