From 88f3c44126ea215ff7f48802d6626db5b9609a6f Mon Sep 17 00:00:00 2001 From: qydysky Date: Sun, 2 Mar 2025 14:46:44 +0800 Subject: [PATCH] 1 (#32) --- ctx/Ctx.go | 5 ++--- ctx/Ctx_test.go | 60 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 3 deletions(-) diff --git a/ctx/Ctx.go b/ctx/Ctx.go index 361c44c..7dd15d9 100644 --- a/ctx/Ctx.go +++ b/ctx/Ctx.go @@ -54,9 +54,7 @@ func WithWait(sctx context.Context, planNum int32, to ...time.Duration) (dctx co doneWait() if ctxp, ok := sctx.Value(ptr).(*Ctx); ok { - defer func() { - ctxp.r32.Add(-1) - }() + defer ctxp.r32.Add(-1) } if planNum == 0 && ctx.w32.Load() == 0 { return ErrNothingWait @@ -66,6 +64,7 @@ func WithWait(sctx context.Context, planNum int32, to ...time.Duration) (dctx co if len(to) > 0 && time.Since(be) > to[0] { return ErrWaitTo } + time.Sleep(time.Millisecond * 100) runtime.Gosched() } for !ctx.r32.CompareAndSwap(0, -1) { diff --git a/ctx/Ctx_test.go b/ctx/Ctx_test.go index f15c07f..5a83c1b 100644 --- a/ctx/Ctx_test.go +++ b/ctx/Ctx_test.go @@ -7,6 +7,66 @@ import ( "time" ) +func TestMain12(t *testing.T) { + ctx1, done1 := WithWait(context.Background(), 0, time.Second*2) + ctx2, done2 := WithWait(ctx1, 0, time.Second*2) + go func() { + ctx3, done3 := WaitCtx(ctx2) + defer done3() + <-ctx3.Done() + }() + time.Sleep(time.Second) + if e := done2(); e != nil { + t.Fatal(e) + } + if e := done1(); e != nil { + t.Fatal(e) + } +} + +func TestMain11(t *testing.T) { + ctx1, done1 := WithWait(context.Background(), 0, time.Second*2) + ctx2, _ := WithWait(ctx1, 0, time.Second*2) + go func() { + ctx3, done3 := WaitCtx(ctx2) + defer done3() + <-ctx3.Done() + }() + time.Sleep(time.Second) + if e := done1(); e == nil { + t.Fatal(e) + } +} + +func TestMain10(t *testing.T) { + ctx1, done := WithWait(context.Background(), 0, time.Second*2) + go func() { + ctx2, done2 := WaitCtx(ctx1) + _, done3 := WaitCtx(ctx2) + defer done2() + defer done3() + <-ctx2.Done() + }() + time.Sleep(time.Second) + if e := done(); e != nil { + t.Fatal(e) + } +} + +func TestMain9(t *testing.T) { + ctx1, done := WithWait(context.Background(), 0, time.Second*2) + go func() { + ctx2, done2 := WaitCtx(ctx1) + _, _ = WaitCtx(ctx2) + defer done2() + <-ctx2.Done() + }() + time.Sleep(time.Second) + if e := done(); e == nil { + t.Fatal(e) + } +} + func TestMain(t *testing.T) { ctx1, done := WithWait(context.Background(), 1, time.Second*2) t0 := time.Now() -- 2.39.2