github.com/Benchkram/bob@v0.0.0-20220321080157-7c8f3876e225/pkg/ctl/flag.go (about)

     1  package ctl
     2  
     3  import "sync"
     4  
     5  // flag symbols a busy process with the possibility
     6  // to be called from multiple goroutines multiple times.
     7  type Flag struct {
     8  	bmutex sync.Mutex
     9  	b      bool
    10  }
    11  
    12  // InProgress aquires the flag if not set. Safe for parallel use.
    13  // The caller is responsible to call done in case no error is returned.
    14  func (f *Flag) InProgress() (done func(), err error) {
    15  	f.bmutex.Lock()
    16  	if f.b {
    17  		f.bmutex.Unlock()
    18  		return nil, ErrInProgress
    19  	}
    20  
    21  	f.b = true
    22  	f.bmutex.Unlock()
    23  	return func() {
    24  		f.bmutex.Lock()
    25  		f.b = false
    26  		f.bmutex.Unlock()
    27  	}, nil
    28  }