sync_var.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package syncutils
  2. import "sync"
  3. // WriteVarFunc 回调变量用来写的函数
  4. type WriteVarFunc[T any] func(v T) T
  5. // ReadVarFunc 回调变量用来读的函数
  6. type ReadVarFunc[T any] func(v T)
  7. // SyncVar 线程安全的变量封装
  8. type SyncVar[T any] struct {
  9. writeLocker sync.Locker
  10. readLocker sync.Locker
  11. v T
  12. }
  13. // NewSyncVar 创建线程安全的变量
  14. func NewSyncVar[T any](v T, isRWMutex bool) *SyncVar[T] {
  15. var writeLocker sync.Locker
  16. var readLocker sync.Locker
  17. if !isRWMutex {
  18. mutex := &sync.Mutex{}
  19. writeLocker = mutex
  20. readLocker = mutex
  21. } else {
  22. mutex := &sync.RWMutex{}
  23. writeLocker = mutex
  24. readLocker = mutex.RLocker()
  25. }
  26. return &SyncVar[T]{
  27. writeLocker: writeLocker,
  28. readLocker: readLocker,
  29. v: v,
  30. }
  31. }
  32. // ForWrite 为写而获取变量
  33. func (syncVar *SyncVar[T]) ForWrite(writeVarFunc WriteVarFunc[T]) {
  34. if writeVarFunc == nil {
  35. return
  36. }
  37. syncVar.writeLocker.Lock()
  38. defer syncVar.writeLocker.Unlock()
  39. syncVar.v = writeVarFunc(syncVar.v)
  40. }
  41. // ForRead 为写而获取变量
  42. func (syncVar *SyncVar[T]) ForRead(readVarFunc ReadVarFunc[T]) {
  43. if readVarFunc == nil {
  44. return
  45. }
  46. syncVar.readLocker.Lock()
  47. defer syncVar.readLocker.Unlock()
  48. readVarFunc(syncVar.v)
  49. }