routines.go 505 B

12345678910111213141516171819202122232425262728293031
  1. package threading
  2. import (
  3. "bytes"
  4. "runtime"
  5. "strconv"
  6. "github.com/tal-tech/go-zero/core/rescue"
  7. )
  8. func GoSafe(fn func()) {
  9. go RunSafe(fn)
  10. }
  11. // Only for debug, never use it in production
  12. func RoutineId() uint64 {
  13. b := make([]byte, 64)
  14. b = b[:runtime.Stack(b, false)]
  15. b = bytes.TrimPrefix(b, []byte("goroutine "))
  16. b = b[:bytes.IndexByte(b, ' ')]
  17. // if error, just return 0
  18. n, _ := strconv.ParseUint(string(b), 10, 64)
  19. return n
  20. }
  21. func RunSafe(fn func()) {
  22. defer rescue.Recover()
  23. fn()
  24. }