go-zero/core/threading/routines.go

47 lines
979 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package threading
import (
"bytes"
"context"
2020-07-26 17:09:05 +08:00
"runtime"
"strconv"
"github.com/zeromicro/go-zero/core/rescue"
2020-07-26 17:09:05 +08:00
)
2021-02-08 21:31:56 +08:00
// GoSafe runs the given fn using another goroutine, recovers if fn panics.
2020-07-26 17:09:05 +08:00
func GoSafe(fn func()) {
go RunSafe(fn)
}
// GoSafeCtx runs the given fn using another goroutine, recovers if fn panics with ctx.
func GoSafeCtx(ctx context.Context, fn func()) {
go RunSafeCtx(ctx, fn)
}
2021-02-08 21:31:56 +08:00
// RoutineId is only for debug, never use it in production.
2020-07-26 17:09:05 +08:00
func RoutineId() uint64 {
b := make([]byte, 64)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
// if error, just return 0
n, _ := strconv.ParseUint(string(b), 10, 64)
return n
}
2021-02-08 21:31:56 +08:00
// RunSafe runs the given fn, recovers if fn panics.
2020-07-26 17:09:05 +08:00
func RunSafe(fn func()) {
defer rescue.Recover()
fn()
}
// RunSafeCtx runs the given fn, recovers if fn panics with ctx.
func RunSafeCtx(ctx context.Context, fn func()) {
defer rescue.RecoverCtx(ctx)
fn()
}