util.go 664 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package game
  2. import (
  3. "fmt"
  4. "runtime"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. )
  9. //获取线程ID
  10. func GoID() int {
  11. var buf [64]byte
  12. n := runtime.Stack(buf[:], false)
  13. idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
  14. id, err := strconv.Atoi(idField)
  15. if err != nil {
  16. panic(fmt.Sprintf("cannot get goroutine id: %v", err))
  17. }
  18. return id
  19. }
  20. var _uuidIntMap = make(map[string]int)
  21. var _uuidIntLock sync.Mutex
  22. //获取int型的自增ID
  23. func GetUuidInt(key string) int {
  24. _uuidIntLock.Lock()
  25. id := _uuidIntMap[key]
  26. nextID := id + 1
  27. if nextID > 1000000000 {
  28. nextID = 0
  29. }
  30. _uuidIntMap[key] = nextID
  31. _uuidIntLock.Unlock()
  32. return id
  33. }