rwmutex.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. // Package rwmutex provides switch of concurrent safety feature for sync.RWMutex.
  7. package rwmutex
  8. import (
  9. "sync"
  10. )
  11. // RWMutex is a sync.RWMutex with a switch for concurrent safe feature.
  12. // If its attribute *sync.RWMutex is not nil, it means it's in concurrent safety usage.
  13. // Its attribute *sync.RWMutex is nil in default, which makes this struct mush lightweight.
  14. type RWMutex struct {
  15. // Underlying mutex.
  16. mutex *sync.RWMutex
  17. }
  18. // New creates and returns a new *RWMutex.
  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) *RWMutex {
  22. mu := Create(safe...)
  23. return &mu
  24. }
  25. // Create creates and returns a new RWMutex object.
  26. // The parameter `safe` is used to specify whether using this mutex in concurrent safety,
  27. // which is false in default.
  28. func Create(safe ...bool) RWMutex {
  29. if len(safe) > 0 && safe[0] {
  30. return RWMutex{
  31. mutex: new(sync.RWMutex),
  32. }
  33. }
  34. return RWMutex{}
  35. }
  36. // IsSafe checks and returns whether current mutex is in concurrent-safe usage.
  37. func (mu *RWMutex) IsSafe() bool {
  38. return mu.mutex != nil
  39. }
  40. // Lock locks mutex for writing.
  41. // It does nothing if it is not in concurrent-safe usage.
  42. func (mu *RWMutex) Lock() {
  43. if mu.mutex != nil {
  44. mu.mutex.Lock()
  45. }
  46. }
  47. // Unlock unlocks mutex for writing.
  48. // It does nothing if it is not in concurrent-safe usage.
  49. func (mu *RWMutex) Unlock() {
  50. if mu.mutex != nil {
  51. mu.mutex.Unlock()
  52. }
  53. }
  54. // RLock locks mutex for reading.
  55. // It does nothing if it is not in concurrent-safe usage.
  56. func (mu *RWMutex) RLock() {
  57. if mu.mutex != nil {
  58. mu.mutex.RLock()
  59. }
  60. }
  61. // RUnlock unlocks mutex for reading.
  62. // It does nothing if it is not in concurrent-safe usage.
  63. func (mu *RWMutex) RUnlock() {
  64. if mu.mutex != nil {
  65. mu.mutex.RUnlock()
  66. }
  67. }