68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"runtime/debug"
|
|
"stat/common/log"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
routinePanicHandler func(string)
|
|
routineCount int64
|
|
)
|
|
|
|
func SetPanicHandler(handler func(string)) {
|
|
routinePanicHandler = handler
|
|
}
|
|
|
|
func Go(f func()) {
|
|
atomic.AddInt64(&routineCount, 1)
|
|
go func() {
|
|
defer func() {
|
|
atomic.AddInt64(&routineCount, -1)
|
|
if r := recover(); r != nil {
|
|
log.Error("【Warning】server occur error,please attention", log.Any("Detail", r))
|
|
if routinePanicHandler != nil {
|
|
routinePanicHandler(fmt.Sprintf("[Panic] routineCount:%d \n err: %+v\n", routineCount, r) + string(debug.Stack()))
|
|
}
|
|
}
|
|
}()
|
|
f()
|
|
}()
|
|
}
|
|
|
|
func GoParam(i int, f func(i int)) {
|
|
atomic.AddInt64(&routineCount, 1)
|
|
go func(i int) {
|
|
defer func() {
|
|
atomic.AddInt64(&routineCount, -1)
|
|
if r := recover(); r != nil {
|
|
log.Error("【Warning】serevr occour error,please attention", log.Any("Detail", r))
|
|
if routinePanicHandler != nil {
|
|
routinePanicHandler(fmt.Sprintf("[Panic] routineCount:%d \n err: %+v\n", routineCount, r) + string(debug.Stack()))
|
|
}
|
|
}
|
|
}()
|
|
f(i)
|
|
}(i)
|
|
}
|
|
|
|
// WaitGoQuit 等待go退出,timeoutSec 超时秒数,<=0表示不超时
|
|
func WaitGoQuit(timeoutSec int32) {
|
|
for {
|
|
count := atomic.LoadInt64(&routineCount)
|
|
if count == 0 {
|
|
return
|
|
}
|
|
time.Sleep(time.Second)
|
|
if timeoutSec > 0 {
|
|
timeoutSec--
|
|
if timeoutSec == 0 {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|