routines.go 648 B

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