github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/lockutil/lockutil.go (about)

     1  // Copyright 2023 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lockutil
    16  
    17  import (
    18  	"errors"
    19  	"sync"
    20  )
    21  
    22  // ErrMutexNotLocked is the error returned by AssertRWMutexIsLocked if the specified mutex was not locked.
    23  var ErrMutexNotLocked = errors.New("mutex is not locked")
    24  
    25  // AssertRWMutexIsLocked checks if |mu| is locked (without deadlocking if the mutex is locked) and returns nil
    26  // the mutex is locked. If the mutex is NOT locked, the ErrMutexNotLocked error is returned.
    27  func AssertRWMutexIsLocked(mu *sync.RWMutex) error {
    28  	// TryLock allows us to validate that the mutex is locked (without actually locking it and causing a
    29  	// deadlock) and to return an error if we detect that the mutex is NOT locked.
    30  	if mu.TryLock() {
    31  		// If TryLock returns true, that means it was able to successfully acquire the lock on the mutex, which
    32  		// means the caller did NOT have the lock when they called this function, so we return an error, and we
    33  		// also need to release the lock on the mutex that we grabbed while testing whether the mutex was locked.
    34  		defer mu.Unlock()
    35  		return ErrMutexNotLocked
    36  	}
    37  	return nil
    38  }