From 8c4e92f5ef268d5f97a06621e820b22a8580089e Mon Sep 17 00:00:00 2001 From: gazebo Date: Fri, 29 Jun 2018 09:18:09 +0800 Subject: [PATCH] - handle panic in routine pool. --- utils/routinepool/routinepool.go | 24 +++++++++++++++++------- utils/routinepool/routinepool_test.go | 8 ++++---- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/utils/routinepool/routinepool.go b/utils/routinepool/routinepool.go index 018f0ce8..8135fa1f 100644 --- a/utils/routinepool/routinepool.go +++ b/utils/routinepool/routinepool.go @@ -4,8 +4,6 @@ import ( "crypto/md5" "encoding/binary" "fmt" - - "git.rosy.net.cn/baseapi" ) const ( @@ -44,19 +42,28 @@ func New(minRoutineCount, maxRoutineCount int) *Pool { return retVal } +func callHandler(handler func()) (retVal interface{}) { + defer func() { + if r := recover(); r != nil { + retVal = r + } + }() + handler() + return retVal +} + func taskFun(taskChan chan *TaskParam, index int) { for { taskParam := <-taskChan - baseapi.SugarLogger.Debugf("routine:%d, handle task:%v", index, taskParam.handler) - taskParam.handler() - taskParam.resultChan <- "" + // baseapi.SugarLogger.Debugf("routine:%d, handle task:%v", index, taskParam.handler) + taskParam.resultChan <- callHandler(taskParam.handler) } } func (p *Pool) CallFun(func4Call func(), primaryID string) { if p.curRoutineCount > 0 { result := md5.Sum([]byte(primaryID)) - resultInt64 := int64(binary.LittleEndian.Uint32(result[:8])) + resultInt64 := int64(binary.LittleEndian.Uint32(result[8:])) chanIndex := int(resultInt64 % int64(p.curRoutineCount)) chanParam := &TaskParam{ @@ -64,7 +71,10 @@ func (p *Pool) CallFun(func4Call func(), primaryID string) { resultChan: make(chan interface{}), } p.taskChans[chanIndex] <- chanParam - _ = <-chanParam.resultChan + r := <-chanParam.resultChan + if r != nil { + panic(r) + } } else { func4Call() } diff --git a/utils/routinepool/routinepool_test.go b/utils/routinepool/routinepool_test.go index 3edbfa3a..55763f2d 100644 --- a/utils/routinepool/routinepool_test.go +++ b/utils/routinepool/routinepool_test.go @@ -23,12 +23,12 @@ func init() { } func TestCallFun(t *testing.T) { - pool := New(10, 10) - for i := 0; i < 20; i++ { + pool := New(1000, 1000) + for i := 0; i < 200; i++ { + x := rand.Int() pool.CallFun(func() { - x := i sugarLogger.Debug(x) - }, utils.Int2Str(i)) + }, utils.Int2Str(x)) } pool.CallFun(func() { sugarLogger.Debug(15)