rwmutex.go 2.0 KB

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