]> 127.0.0.1 Git - part/.git/commitdiff
funcCtrl N v0.5.20
authorqydysky <qydysky@foxmail.com>
Tue, 1 Jun 2021 15:31:32 +0000 (23:31 +0800)
committerqydysky <qydysky@foxmail.com>
Tue, 1 Jun 2021 15:31:32 +0000 (23:31 +0800)
funcCtrl/FuncCtrl.go
funcCtrl/FuncCtrl_test.go

index 053283e8fe5a568e9d56d14cadc3df86a135b724..f34e92986fd17fc9e25d1bb52ddfbf7fced21ea8 100644 (file)
@@ -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
index 8e331bf5afd5a42e780aa228069124eb84ff6be8..d8f0052a43c6fff8646e4e69015c9a23e6805505 100644 (file)
@@ -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