...

Source file src/oss.terrastruct.com/util-go/xcontext/mutex.go

Documentation: oss.terrastruct.com/util-go/xcontext

     1  package xcontext
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  )
     7  
     8  type Mutex struct {
     9  	ch chan struct{}
    10  }
    11  
    12  func NewMutex() *Mutex {
    13  	return &Mutex{
    14  		ch: make(chan struct{}, 1),
    15  	}
    16  }
    17  
    18  func (m *Mutex) TryLock() bool {
    19  	select {
    20  	case m.ch <- struct{}{}:
    21  		return true
    22  	default:
    23  		return false
    24  	}
    25  }
    26  
    27  func (m *Mutex) Lock(ctx context.Context) error {
    28  	select {
    29  	case <-ctx.Done():
    30  		return fmt.Errorf("failed to acquire lock: %w", ctx.Err())
    31  	case m.ch <- struct{}{}:
    32  		return nil
    33  	}
    34  }
    35  
    36  func (m *Mutex) Unlock() {
    37  	select {
    38  	case <-m.ch:
    39  	default:
    40  		panic("xcontext.Mutex: Unlock before Lock")
    41  	}
    42  }
    43  

View as plain text