add new function g.Go (#2943)

This commit is contained in:
John Guo
2023-09-11 10:18:44 +08:00
committed by GitHub
parent 1582714325
commit ab1970e7d6
7 changed files with 291 additions and 128 deletions

View File

@ -17,6 +17,20 @@ import (
"github.com/gogf/gf/v2/util/gutil"
)
type (
Func = gutil.Func // Func is the function which contains context parameter.
RecoverFunc = gutil.RecoverFunc // RecoverFunc is the panic recover function which contains context parameter.
)
// Go creates a new asynchronous goroutine function with specified recover function.
//
// The parameter `recoverFunc` is called when any panic during executing of `goroutineFunc`.
// If `recoverFunc` is given nil, it ignores the panic from `goroutineFunc` and no panic will
// throw to parent goroutine.
func Go(ctx context.Context, goroutineFunc Func, recoverFunc RecoverFunc) {
gutil.Go(ctx, goroutineFunc, recoverFunc)
}
// NewVar returns a gvar.Var.
func NewVar(i interface{}, safe ...bool) *Var {
return gvar.New(i, safe...)

View File

@ -9,8 +9,10 @@ package g_test
import (
"context"
"os"
"sync"
"testing"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/util/gutil"
@ -114,3 +116,19 @@ func Test_Object(t *testing.T) {
t.AssertNE(g.Validator(), nil)
})
}
func Test_Go(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
wg = sync.WaitGroup{}
array = garray.NewArray(true)
)
wg.Add(1)
g.Go(context.Background(), func(ctx context.Context) {
defer wg.Done()
array.Append(1)
}, nil)
wg.Wait()
t.Assert(array.Len(), 1)
})
}