github.com/msales/pkg/v3@v3.24.0/syncx/mutex.go (about)

     1  package syncx
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"unsafe"
     7  )
     8  
     9  const (
    10  	mutexLocked = 1 << iota
    11  )
    12  
    13  // Mutex is simple sync.Mutex with the ability to try to Lock.
    14  type Mutex struct {
    15  	in sync.Mutex
    16  }
    17  
    18  // Lock locks m.
    19  // If the lock is already in use, the calling goroutine
    20  // blocks until the mutex is available.
    21  func (m *Mutex) Lock() {
    22  	m.in.Lock()
    23  }
    24  
    25  // Unlock unlocks m.
    26  // It is a run-time error if m is not locked on entry to Unlock.
    27  //
    28  // A locked Mutex is not associated with a particular goroutine.
    29  // It is allowed for one goroutine to lock a Mutex and then
    30  // arrange for another goroutine to unlock it.
    31  func (m *Mutex) Unlock() {
    32  	m.in.Unlock()
    33  }
    34  
    35  // TryLock tries to lock m. It returns true in case of success, false otherwise.
    36  func (m *Mutex) TryLock() bool {
    37  	return atomic.CompareAndSwapInt32((*int32)(unsafe.Pointer(&m.in)), 0, mutexLocked)
    38  }