routines.go 987 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package threading
  2. import (
  3. "bytes"
  4. "context"
  5. "runtime"
  6. "strconv"
  7. "github.com/wuntsong-org/go-zero-plus/core/rescue"
  8. )
  9. // GoSafe runs the given fn using another goroutine, recovers if fn panics.
  10. func GoSafe(fn func()) {
  11. go RunSafe(fn)
  12. }
  13. // GoSafeCtx runs the given fn using another goroutine, recovers if fn panics with ctx.
  14. func GoSafeCtx(ctx context.Context, fn func()) {
  15. go RunSafeCtx(ctx, fn)
  16. }
  17. // RoutineId is only for debug, never use it in production.
  18. func RoutineId() uint64 {
  19. b := make([]byte, 64)
  20. b = b[:runtime.Stack(b, false)]
  21. b = bytes.TrimPrefix(b, []byte("goroutine "))
  22. b = b[:bytes.IndexByte(b, ' ')]
  23. // if error, just return 0
  24. n, _ := strconv.ParseUint(string(b), 10, 64)
  25. return n
  26. }
  27. // RunSafe runs the given fn, recovers if fn panics.
  28. func RunSafe(fn func()) {
  29. defer rescue.Recover()
  30. fn()
  31. }
  32. // RunSafeCtx runs the given fn, recovers if fn panics with ctx.
  33. func RunSafeCtx(ctx context.Context, fn func()) {
  34. defer rescue.RecoverCtx(ctx)
  35. fn()
  36. }