From 05507db89e555b9fd5b843fd17a0aaf3d35f1ec1 Mon Sep 17 00:00:00 2001 From: qydysky Date: Tue, 1 Jun 2021 23:31:32 +0800 Subject: [PATCH] funcCtrl N --- funcCtrl/FuncCtrl.go | 36 ++++++++++++++++++++++++++++++++++++ funcCtrl/FuncCtrl_test.go | 18 ++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/funcCtrl/FuncCtrl.go b/funcCtrl/FuncCtrl.go index 053283e..f34e929 100644 --- a/funcCtrl/FuncCtrl.go +++ b/funcCtrl/FuncCtrl.go @@ -3,6 +3,7 @@ package part import ( "sync" "unsafe" + "runtime" "sync/atomic" "container/list" idpool "github.com/qydysky/part/idpool" @@ -54,4 +55,39 @@ func (t *BlockFunc) Block() { func (t *BlockFunc) UnBlock() { t.Unlock() +} + +type BlockFuncN struct{//新的等待旧的 个数 + n int64 + Max int64 +} + +func (t *BlockFuncN) Block() { + for { + now := atomic.LoadInt64(&t.n) + if now < t.Max && now >= 0 {break} + runtime.Gosched() + } + atomic.AddInt64(&t.n, 1) +} + +func (t *BlockFuncN) UnBlock() { + for { + now := atomic.LoadInt64(&t.n) + if now > 0 {break} + runtime.Gosched() + } + atomic.AddInt64(&t.n, -1) +} + +func (t *BlockFuncN) None() { + for !atomic.CompareAndSwapInt64(&t.n, 0, -1) { + runtime.Gosched() + } +} + +func (t *BlockFuncN) UnNone() { + for !atomic.CompareAndSwapInt64(&t.n, -1, 0) { + runtime.Gosched() + } } \ No newline at end of file diff --git a/funcCtrl/FuncCtrl_test.go b/funcCtrl/FuncCtrl_test.go index 8e331bf..d8f0052 100644 --- a/funcCtrl/FuncCtrl_test.go +++ b/funcCtrl/FuncCtrl_test.go @@ -50,4 +50,22 @@ func Test_BlockFunc(t *testing.T) { go a(1) go a(2) time.Sleep(5*time.Second) +} + +func Test_BlockFuncN(t *testing.T) { + var b = BlockFuncN{ + Max:2, + } + var a = func(i int){ + b.Block() + defer b.UnBlock() + t.Log(i,`.`) + time.Sleep(time.Second) + t.Log(i,`.`) + } + t.Log(`show two . at one time`) + go a(1) + go a(2) + go a(3) + time.Sleep(5*time.Second) } \ No newline at end of file -- 2.39.2