async

package
v0.0.0-...-29d029c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2023 License: BSD-3-Clause Imports: 5 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultGraceful = Graceful{/* contains filtered or unexported fields */}

DefaultGraceful 默认的Graceful

Functions

func Parallel

func Parallel(funcs ...func() error) error

Parallel 并行执行一组函数,等待执行完成。 如果其中一个或多个函数返回错误,未执行的函数不再执行,并优先选择前面函数的错误返回。 如果其中一个或多个函数panic,未执行的函数不再执行,并优先选择前面函数的recover()的非nil结果再次panic。

Example
err := Parallel(func() error {
	fmt.Println("I am a concurrently executed task")
	return nil
}, func() error {
	fmt.Println("I am a concurrently executed task")
	return nil
}, func() error {
	fmt.Println("I am a concurrently executed task")
	return fmt.Errorf("a little exception")
})

if err != nil {
	fmt.Println(err)
}
Output:

I am a concurrently executed task
I am a concurrently executed task
I am a concurrently executed task
a little exception

func ParallelLimit

func ParallelLimit(limit int, funcs ...func() error) error

ParallelLimit 并行执行一组函数,等待执行完成。 每次调用最多只执行limit路并发执行。前面的函数优先执行。 如果其中一个或多个函数返回错误,未执行的函数不再执行,并优先选择前面函数的错误返回。 如果其中一个或多个函数panic,未执行的函数不再执行,并优先选择前面函数的recover()的非nil结果再次panic。

func Series

func Series(funcs ...func() error) error

Series 串行执行一组函数,直至出错或者执行完。

Example
err := Series(func() error {
	fmt.Println("one")
	return nil
}, func() error {
	fmt.Println("two")
	return nil
}, func() error {
	fmt.Println("three")
	return fmt.Errorf("Failed")
}, func() error {
	fmt.Println("four")
	return nil
})

if err != nil {
	fmt.Println(err)
}
Output:

one
two
three
Failed

Types

type Graceful

type Graceful struct {
	// contains filtered or unexported fields
}

Graceful 运行并graceful退出。

Example
go func() {
	DefaultGraceful.Run(func() {
		// nothing
	})
}()

branch := DefaultGraceful.NewBranch("branch_1")
go func() {
	branch.Run(func() {
		time.Sleep(time.Millisecond * 500)
	})
}()

// 等待两个goroutine已经运行
time.Sleep(time.Millisecond * 100)

// 程序退出时……

ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100)
defer cancel()
err := DefaultGraceful.Wait(ctx)
if err != nil {
	fmt.Println(err)

	busyBranches := DefaultGraceful.BusyBranches()
	fmt.Println(busyBranches)

	// 直接结束进程,不再等待分支Run的过程
}
Output:

context deadline exceeded
[branch_1]

func (*Graceful) BusyBranches

func (graceful *Graceful) BusyBranches() []string

BusyBranches 忙碌中的分支。

func (*Graceful) NewBranch

func (graceful *Graceful) NewBranch(name string) *Graceful

NewBranch 新建一个分支。

func (*Graceful) Run

func (graceful *Graceful) Run(f func())

Run 新运行一个函数。

func (*Graceful) Wait

func (graceful *Graceful) Wait(ctx context.Context) error

Wait 等待所有当前Graceful对象运行的函数退出,或者ctx错误。 执行Wait时,不应该再执行当前Graceful对象和Branch对象的Run。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL