]> 127.0.0.1 Git - part/.git/commitdiff
update
authorqydysky <qydysky@foxmail.com>
Sat, 8 Apr 2023 13:09:17 +0000 (21:09 +0800)
committerqydysky <qydysky@foxmail.com>
Sat, 8 Apr 2023 13:09:17 +0000 (21:09 +0800)
funcCtrl/FuncCtrl.go
funcCtrl/FuncCtrl_test.go

index 26aca3146edc14f7cd7e4aebbe0aaa9392a93bf7..7648c45cdd970ba2f8e8c712a293675a28da562e 100644 (file)
@@ -1,6 +1,7 @@
 package part
 
 import (
+       "context"
        "runtime"
        "sync"
        "sync/atomic"
@@ -23,11 +24,16 @@ func (t *SkipFunc) UnSet() {
 // 新的替换旧的
 type FlashFunc struct {
        b atomic.Uintptr
+       c *context.CancelFunc
 }
 
 func (t *FlashFunc) Flash() (current uintptr) {
        current = uintptr(unsafe.Pointer(&struct{}{}))
        t.b.Store(current)
+       if t.c != nil {
+               (*t.c)()
+               t.c = nil
+       }
        return
 }
 
@@ -37,6 +43,18 @@ func (t *FlashFunc) NeedExit(current uintptr) bool {
        return t.b.Load() != current
 }
 
+func (t *FlashFunc) FlashWithContext() (current uintptr, c context.Context) {
+       current = uintptr(unsafe.Pointer(&struct{}{}))
+       t.b.Store(current)
+       if t.c != nil {
+               (*t.c)()
+               t.c = nil
+       }
+       c, cancle := context.WithCancel(context.Background())
+       t.c = &cancle
+       return
+}
+
 // 新的等待旧的
 type BlockFunc struct {
        sync.Mutex
index 13de5b9430ea6f3bc7cad8d4d4eb5b3652ef5d12..6d7a4f5cc6cdb30e9dd640eda3dfcb5ac4775bc8 100644 (file)
@@ -44,6 +44,23 @@ func Test_FlashFunc(t *testing.T) {
        }
 }
 
+func Test_FlashFunc2(t *testing.T) {
+       var cc = make(chan int, 2)
+       var b FlashFunc
+       var a = func(i int) {
+               _, c := b.FlashWithContext()
+               <-c.Done()
+               cc <- i
+       }
+       go a(1)
+       go a(2)
+       go a(3)
+       time.Sleep(time.Second)
+       if len(cc) != 2 && <-cc != 1 && <-cc != 2 {
+               t.Fatal(len(cc))
+       }
+}
+
 func Test_BlockFunc(t *testing.T) {
        var c = make(chan int, 2)
        var b BlockFunc