userSyncMap.go 726 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package common
  2. import (
  3. "app.yhyue.com/moapp/MessageCenter/rpc/internal/config"
  4. "fmt"
  5. "hash/fnv"
  6. "sync"
  7. )
  8. var UserLocksMap *UserLocks
  9. type UserLocks struct {
  10. locks []*sync.Mutex
  11. mutex sync.Mutex
  12. }
  13. func NewUserLocks() *UserLocks {
  14. locks := make([]*sync.Mutex, config.ConfigJson.ThreadCount)
  15. for i := range locks {
  16. locks[i] = &sync.Mutex{}
  17. }
  18. return &UserLocks{
  19. locks: locks,
  20. }
  21. }
  22. func (ul *UserLocks) GetLock(userID string) *sync.Mutex {
  23. hash := hashUserID(userID)
  24. ul.mutex.Lock()
  25. defer ul.mutex.Unlock()
  26. index := hash % uint32(len(ul.locks))
  27. fmt.Println("index", index)
  28. return ul.locks[index]
  29. }
  30. func hashUserID(userID string) uint32 {
  31. h := fnv.New32a()
  32. h.Write([]byte(userID))
  33. return h.Sum32()
  34. }