// do something..
// <-ctx1.Done() // wait mainDone call
// }()
+//
+// or
+// use as a normal context.WithCancel(ctx)
func WaitCtx(ctx context.Context) (dctx context.Context, done func()) {
- if ctxp, ok := ctx.Value(ptr).(*Ctx); ok {
+ ctx1, done1 := context.WithCancel(ctx)
+ if ctxp, ok := ctx1.Value(ptr).(*Ctx); ok {
ctxp.r32.Add(1)
ctxp.w32.Add(-1)
}
- return ctx, func() {
- if ctxp, ok := ctx.Value(ptr).(*Ctx); ok {
+ return ctx1, func() {
+ done1()
+ if ctxp, ok := ctx1.Value(ptr).(*Ctx); ok {
ctxp.r32.Add(-1)
}
}
)
func TestMain(t *testing.T) {
- ctx1, done := WithWait(context.Background(), 1, time.Second)
+ ctx1, done := WithWait(context.Background(), 1, time.Second*2)
t0 := time.Now()
go func() {
ctx2, done1 := WaitCtx(ctx1)
if time.Since(t0) < time.Millisecond*100 {
t.Fail()
}
+ time.Sleep(time.Second)
+ }()
+ time.Sleep(time.Second)
+ t1 := time.Now()
+ if done() != nil {
+ t.Fatal()
+ }
+ if time.Since(t1) < time.Second {
+ t.Fail()
+ }
+}
+
+func TestMain5(t *testing.T) {
+ ctx1, done := WithWait(context.Background(), 1, time.Second*2)
+ go func() {
+ ctx2, done1 := WaitCtx(ctx1)
+ go func() {
+ time.Sleep(time.Millisecond * 500)
+ done1()
+ }()
+ t1 := time.Now()
+ <-ctx2.Done()
+ if time.Since(t1)-time.Millisecond*500 > time.Millisecond*100 {
+ t.Fatal()
+ }
+ time.Sleep(time.Second)
}()
time.Sleep(time.Second)
+ t1 := time.Now()
if done() != nil {
t.Fatal()
}
+ if time.Since(t1) > time.Second {
+ t.Fatal()
+ }
}
func TestMain1(t *testing.T) {
import (
"reflect"
+ "time"
)
//语法糖
-//数组切片,重新分配内存
+// 数组切片,重新分配内存
// i := []int{0,1,2}
// b := SliceCut(i[:1]).([]int)
func SliceCopy(src interface{}) (des interface{}) {
srcV := reflect.ValueOf(src)
- if sk := srcV.Kind();sk != reflect.Slice && sk != reflect.Array {
- panic(&reflect.ValueError{Method:"reflect.Copy", Kind:sk})
+ if sk := srcV.Kind(); sk != reflect.Slice && sk != reflect.Array {
+ panic(&reflect.ValueError{Method: "reflect.Copy", Kind: sk})
}
- desV := reflect.MakeSlice(srcV.Type(),srcV.Len(),srcV.Len())
+ desV := reflect.MakeSlice(srcV.Type(), srcV.Len(), srcV.Len())
reflect.Copy(desV, srcV)
des = desV.Interface()
return
}
+func Callback(f func(startT time.Time, args ...any)) func(args ...any) {
+ now := time.Now()
+ return func(args ...any) {
+ f(now, args...)
+ }
+}