From 3395ef9ce3e02440d623d7fecab1b3a5513c6e2c Mon Sep 17 00:00:00 2001 From: qydysky Date: Tue, 23 Feb 2021 01:23:17 +0800 Subject: [PATCH] =?utf8?q?tmplK=E6=88=96=E5=AD=98=E5=9C=A8=E4=B8=A5?= =?utf8?q?=E9=87=8D=E9=97=AE=E9=A2=98=EF=BC=8C=E4=BD=BF=E7=94=A8funcCtrl?= =?utf8?q?=E6=9B=BF=E4=BB=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- funcCtrl/FuncCtrl.go | 53 +++++++++++++++++++++++++++++++++++++++ funcCtrl/FuncCtrl_test.go | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 funcCtrl/FuncCtrl.go create mode 100644 funcCtrl/FuncCtrl_test.go diff --git a/funcCtrl/FuncCtrl.go b/funcCtrl/FuncCtrl.go new file mode 100644 index 0000000..be2563f --- /dev/null +++ b/funcCtrl/FuncCtrl.go @@ -0,0 +1,53 @@ +package part + +import ( + "sync" + "unsafe" + "sync/atomic" + "container/list" + idpool "github.com/qydysky/part/idpool" +) + +type SkipFunc struct{//新的跳过 + c unsafe.Pointer +} + +func (t *SkipFunc) NeedSkip() (result bool) { + return !atomic.CompareAndSwapPointer(&t.c, nil, unsafe.Pointer(&struct{}{})) +} + +func (t *SkipFunc) UnSet() { + atomic.CompareAndSwapPointer(&t.c, atomic.LoadPointer(&t.c), nil) +} + +type FlashFunc struct{//新的替换旧的 + b *list.List + pool *idpool.Idpool +} + +func (t *FlashFunc) Flash() (current uintptr) { + if t.pool == nil {t.pool = idpool.New()} + if t.b == nil {t.b = list.New()} + + e := t.pool.Get() + current = e.Id + t.b.PushFront(e) + + return +} + +func (t *FlashFunc) NeedExit(current uintptr) (bool) { + return current != t.b.Front().Value.(*idpool.Id).Id +} + +type BlockFunc struct{//新的等待旧的 + sync.Mutex +} + +func (t *BlockFunc) Block() { + t.Lock() +} + +func (t *BlockFunc) UnBlock() { + t.Unlock() +} \ No newline at end of file diff --git a/funcCtrl/FuncCtrl_test.go b/funcCtrl/FuncCtrl_test.go new file mode 100644 index 0000000..801cdae --- /dev/null +++ b/funcCtrl/FuncCtrl_test.go @@ -0,0 +1,51 @@ +package part + +import ( + "testing" + "time" +) + +func Test_SkipFunc(t *testing.T) { + var b SkipFunc + var a = func(i int){ + if b.NeedSkip() {return} + defer b.UnSet() + t.Log(i,`.`) + time.Sleep(time.Second) + t.Log(i,`..`) + } + t.Log(`just show 1 or 2 twice`) + go a(1) + go a(2) + time.Sleep(5*time.Second) +} + +func Test_FlashFunc(t *testing.T) { + var b FlashFunc + var a = func(i int){ + id := b.Flash() + t.Log(i,`.`) + time.Sleep(time.Second) + if b.NeedExit(id) {return} + t.Log(i,`.`) + } + t.Log(`show 1 or 2, then show the other twice`) + go a(1) + go a(2) + time.Sleep(5*time.Second) +} + +func Test_BlockFunc(t *testing.T) { + var b BlockFunc + var a = func(i int){ + b.Block() + defer b.UnBlock() + t.Log(i,`.`) + time.Sleep(time.Second) + t.Log(i,`.`) + } + t.Log(`show 1 and 2 twice`) + go a(1) + go a(2) + time.Sleep(5*time.Second) +} \ No newline at end of file -- 2.39.2