github.com/diamondburned/arikawa/v2@v2.1.0/internal/moreatomic/mutex.go (about)

     1  package moreatomic
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  type CtxMutex struct {
     8  	mut chan struct{}
     9  }
    10  
    11  func NewCtxMutex() *CtxMutex {
    12  	return &CtxMutex{
    13  		mut: make(chan struct{}, 1),
    14  	}
    15  }
    16  
    17  // func (m *CtxMutex) TryLock() bool {
    18  // 	select {
    19  // 	case m.mut <- struct{}{}:
    20  // 		return true
    21  // 	default:
    22  // 		return false
    23  // 	}
    24  // }
    25  
    26  // func (m *CtxMutex) IsBusy() bool {
    27  // 	select {
    28  // 	case m.mut <- struct{}{}:
    29  // 		<-m.mut
    30  // 		return false
    31  // 	default:
    32  // 		return true
    33  // 	}
    34  // }
    35  
    36  func (m *CtxMutex) Lock(ctx context.Context) error {
    37  	select {
    38  	case m.mut <- struct{}{}:
    39  		return nil
    40  	case <-ctx.Done():
    41  		return ctx.Err()
    42  	}
    43  }
    44  
    45  // TryUnlock returns true if the mutex has been unlocked.
    46  func (m *CtxMutex) TryUnlock() bool {
    47  	select {
    48  	case <-m.mut:
    49  		return true
    50  	default:
    51  		return false
    52  	}
    53  }
    54  
    55  func (m *CtxMutex) Unlock() {
    56  	select {
    57  	case <-m.mut:
    58  		// return
    59  	default:
    60  		panic("Unlock of already unlocked mutex.")
    61  	}
    62  }