1 Star 0 Fork 0

非空非零 / jupiter

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
goroutine.go 2.47 KB
一键复制 编辑 原始数据 按行查看 历史
renzhentao 提交于 2021-06-21 15:02 . 1
// Copyright 2020 Douyu
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package xgo
import (
"fmt"
"runtime"
"sync"
"time"
"gitee.com/nonull/eden/pkg/xlog"
"github.com/codegangsta/inject"
)
// Serial 串行
func Serial(fns ...func()) func() {
return func() {
for _, fn := range fns {
fn()
}
}
}
// Parallel 并发执行
func Parallel(fns ...func()) func() {
var wg sync.WaitGroup
return func() {
wg.Add(len(fns))
for _, fn := range fns {
go try2(fn, wg.Done)
}
wg.Wait()
}
}
// RestrictParallel 并发,最大并发量restrict
func RestrictParallel(restrict int, fns ...func()) func() {
var channel = make(chan struct{}, restrict)
return func() {
var wg sync.WaitGroup
for _, fn := range fns {
wg.Add(1)
go func(fn func()) {
defer wg.Done()
channel <- struct{}{}
try2(fn, nil)
<-channel
}(fn)
}
wg.Wait()
close(channel)
}
}
// GoDirect ...
func GoDirect(fn interface{}, args ...interface{}) {
var inj = inject.New()
for _, arg := range args {
inj.Map(arg)
}
_, file, line, _ := runtime.Caller(1)
go func() {
defer func() {
if err := recover(); err != nil {
_logger.Error("recover", xlog.Any("err", err), xlog.String("line", fmt.Sprintf("%s:%d", file, line)))
}
}()
// 忽略返回值, goroutine执行的返回值通常都会忽略掉
_, err := inj.Invoke(fn)
if err != nil {
_logger.Error("inject", xlog.Any("err", err), xlog.String("line", fmt.Sprintf("%s:%d", file, line)))
return
}
}()
}
// Go goroutine
func Go(fn func()) {
go try2(fn, nil)
}
// DelayGo goroutine
func DelayGo(delay time.Duration, fn func()) {
_, file, line, _ := runtime.Caller(1)
go func() {
defer func() {
if err := recover(); err != nil {
_logger.Error("recover", xlog.Any("err", err), xlog.String("line", fmt.Sprintf("%s:%d", file, line)))
}
}()
time.Sleep(delay)
fn()
}()
}
// SafeGo safe go
func SafeGo(fn func(), rec func(error)) {
go func() {
err := try2(fn, nil)
if err != nil {
rec(err)
}
}()
}
1
https://gitee.com/nonull/eden.git
git@gitee.com:nonull/eden.git
nonull
eden
jupiter
v0.3.1

搜索帮助

53164aa7 5694891 3bd8fe86 5694891