github.com/gogf/gf@v1.16.9/internal/mutex/mutex.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // Package mutex provides switch of concurrent safe feature for sync.Mutex.
     8  package mutex
     9  
    10  import "sync"
    11  
    12  // Mutex is a sync.Mutex with a switch for concurrent safe feature.
    13  type Mutex struct {
    14  	sync.Mutex
    15  	safe bool
    16  }
    17  
    18  // New creates and returns a new *Mutex.
    19  // The parameter `safe` is used to specify whether using this mutex in concurrent-safety,
    20  // which is false in default.
    21  func New(safe ...bool) *Mutex {
    22  	mu := new(Mutex)
    23  	if len(safe) > 0 {
    24  		mu.safe = safe[0]
    25  	} else {
    26  		mu.safe = false
    27  	}
    28  	return mu
    29  }
    30  
    31  func (mu *Mutex) IsSafe() bool {
    32  	return mu.safe
    33  }
    34  
    35  func (mu *Mutex) Lock() {
    36  	if mu.safe {
    37  		mu.Mutex.Lock()
    38  	}
    39  }
    40  
    41  func (mu *Mutex) Unlock() {
    42  	if mu.safe {
    43  		mu.Mutex.Unlock()
    44  	}
    45  }