github.com/zhiqiangxu/util@v0.0.0-20230112053021-0a7aee056cd5/mutex/cmutex.go (about)

     1  package mutex
     2  
     3  import (
     4  	"context"
     5  
     6  	"golang.org/x/sync/semaphore"
     7  )
     8  
     9  // CMutex implements a cancelable mutex  (in fact also a try-able mutex)
    10  type CMutex struct {
    11  	sema *semaphore.Weighted
    12  }
    13  
    14  // NewCMutex is ctor for CMutex
    15  func NewCMutex() *CMutex {
    16  	return &CMutex{sema: semaphore.NewWeighted(1)}
    17  }
    18  
    19  // Lock with context
    20  func (m *CMutex) Lock(ctx context.Context) (err error) {
    21  	err = m.sema.Acquire(ctx, 1)
    22  	return
    23  }
    24  
    25  // Unlock should only be called after a successful Lock
    26  func (m *CMutex) Unlock() {
    27  	m.sema.Release(1)
    28  }
    29  
    30  // TryLock returns true if lock acquired
    31  func (m *CMutex) TryLock() bool {
    32  	return m.sema.TryAcquire(1)
    33  }