From d9ba073b76a143ef2f29f2609aed90b32d324684 Mon Sep 17 00:00:00 2001 From: qydysky Date: Mon, 9 May 2022 22:17:05 +0800 Subject: [PATCH] BlockFuncN plan --- funcCtrl/FuncCtrl.go | 25 ++++++++++++++++++------- funcCtrl/FuncCtrl_test.go | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/funcCtrl/FuncCtrl.go b/funcCtrl/FuncCtrl.go index 3fd119a..799a1fc 100644 --- a/funcCtrl/FuncCtrl.go +++ b/funcCtrl/FuncCtrl.go @@ -63,9 +63,9 @@ func (t *BlockFunc) UnBlock() { } type BlockFuncN struct { //新的等待旧的 个数 - started int64 - n int64 - Max int64 + plan int64 + n int64 + Max int64 } func (t *BlockFuncN) Block() { @@ -77,7 +77,6 @@ func (t *BlockFuncN) Block() { runtime.Gosched() } atomic.AddInt64(&t.n, 1) - atomic.StoreInt64(&t.started, 1) } func (t *BlockFuncN) UnBlock() { @@ -89,12 +88,12 @@ func (t *BlockFuncN) UnBlock() { runtime.Gosched() } atomic.AddInt64(&t.n, -1) + if atomic.LoadInt64(&t.plan) > 0 { + atomic.AddInt64(&t.plan, -1) + } } func (t *BlockFuncN) None() { - for !atomic.CompareAndSwapInt64(&t.started, 1, 0) { - runtime.Gosched() - } for !atomic.CompareAndSwapInt64(&t.n, 0, -1) { runtime.Gosched() } @@ -105,3 +104,15 @@ func (t *BlockFuncN) UnNone() { runtime.Gosched() } } + +func (t *BlockFuncN) Plan(n int64) { + for !atomic.CompareAndSwapInt64(&t.plan, 0, n) { + runtime.Gosched() + } +} + +func (t *BlockFuncN) PlanDone() { + for atomic.LoadInt64(&t.plan) > 0 { + runtime.Gosched() + } +} diff --git a/funcCtrl/FuncCtrl_test.go b/funcCtrl/FuncCtrl_test.go index 557d1c0..e640372 100644 --- a/funcCtrl/FuncCtrl_test.go +++ b/funcCtrl/FuncCtrl_test.go @@ -76,3 +76,24 @@ func Test_BlockFuncN(t *testing.T) { b.UnNone() t.Log(`fin`) } + +func Test_BlockFuncNPlan(t *testing.T) { + var b = &BlockFuncN{ + Max: 2, + } + var a = func(i int) { + defer b.UnBlock() + b.Block() + t.Log(i, `.`) + time.Sleep(time.Second) + t.Log(i, `.`) + } + t.Log(`show two . at one time`) + b.Plan(4) + go a(0) + go a(1) + go a(2) + go a(3) + b.PlanDone() + t.Log(`fin`) +} -- 2.39.2