From e3171a8b3ee4a3abd763830d0b240f73765003b4 Mon Sep 17 00:00:00 2001 From: HuangJiaLuo <1820799930@qq.com> Date: Thu, 7 Oct 2021 16:30:23 +0800 Subject: [PATCH] feat(event): Add SetResultErr func --- pkg/event/driver.go | 20 +++++++++++++++----- pkg/event/event_test.go | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/pkg/event/driver.go b/pkg/event/driver.go index c6b6838..b5c5636 100644 --- a/pkg/event/driver.go +++ b/pkg/event/driver.go @@ -57,10 +57,6 @@ func (e *Event) GetValue(key string) (interface{}, bool) { return val, ok } -func (e *Event) SetErr(err error) { - e.err = err -} - // InitWaitEvent 初始化 wait event 必须调用才拥有等待特性 func (e *Event) InitWaitEvent() { e.muClose.Lock() @@ -98,14 +94,28 @@ func (e *Event) ExecWorkAndSendResult(work EventWorkFunc) (interface{}, error) { e.eventStatus = workEventState res, err := work() - e.waitResult <- res e.err = err + e.waitResult <- res close(e.waitResult) e.eventStatus = closeEventState return res, err } +func (e *Event) SetResultErr(err error) { + e.muClose.Lock() + defer e.muClose.Unlock() + if e.eventStatus != waitEventState { + return + } + + e.eventStatus = workEventState + e.err = err + e.waitResult <- nil + close(e.waitResult) + e.eventStatus = closeEventState +} + func NewEvent(eventName string) *Event { return &Event{ eventName: eventName, diff --git a/pkg/event/event_test.go b/pkg/event/event_test.go index bf6a6de..8da5b4c 100644 --- a/pkg/event/event_test.go +++ b/pkg/event/event_test.go @@ -3,6 +3,7 @@ package event import ( "context" "fmt" + "gitee.com/timedb/wheatCache/pkg/errorx" "testing" "time" @@ -79,3 +80,20 @@ func waitConsumer(t *testing.T, ctx context.Context, v ConsumerInterface) { }) } } + +func TestEvent_SetResultErr(t *testing.T) { + ctx := context.Background() + event := NewEvent("dddd") + driver := NewDriver(100) + produce := NewProduce(driver) + consumer := NewConsumer(driver) + go func() { + event := consumer.Receive(ctx) + event.SetResultErr(errorx.New("err")) + }() + event.InitWaitEvent() + produce.Call(ctx, event) + _, err := event.StartWaitEvent(2 * time.Second) + fmt.Println(err) + require.Error(t, err) +}