xprocess

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2020 License: MIT Imports: 11 Imported by: 9

README

xprocess

一个通用的机制去管理goroutine的生命周期

  1. 通过xprocess.Go替换原生的直接启动goroutine的方式
  2. 通过context传递, 管理goroutine的生命周期
  3. GoLoop是对goroutine中有for的封装和替换
  4. Group是一个WaitGroup的wrap,不过增加了goroutine统计和可退出机制
  5. Stack会得到内存中所有在运行的goroutine, 以及数量

Examples

fmt.Println(xprocess.Stack())
cancel := xprocess.Go(func(ctx context.Context) error {
    for {
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
            time.Sleep(time.Millisecond * 100)
            fmt.Println("g1")
        }
    }
})

time.Sleep(time.Second)
fmt.Println(xprocess.Stack())
fmt.Println(cancel())
time.Sleep(time.Second)
fmt.Println(xprocess.Stack())
fmt.Println(xprocess.Stack())
for {
    xprocess.Go(func(ctx context.Context) error {
        time.Sleep(time.Second)
        fmt.Println("g2")
        return ctx.Err()
    })
    xprocess.GoLoop(func(ctx context.Context) error {
        time.Sleep(time.Second)
        fmt.Println("g3")
        return ctx.Err()
    })

    g := xprocess.NewGroup()
    g.Go(func(ctx context.Context) error {
        fmt.Println("g4")
        return nil
    })
    g.Go(func(ctx context.Context) error {
        fmt.Println("g5")
        return nil
    })
    g.Go(func(ctx context.Context) error {
        fmt.Println("g6")
        return xerror.Fmt("test error")
    })
    g.Wait()
    fmt.Println(g.Err())

    g.Cancel()

    fmt.Println(xprocess.Stack())
    time.Sleep(time.Second)
}
Timeout
func TestTimeout(t *testing.T) {
	err := xprocess.Timeout(time.Second, func(ctx context.Context) error {
		time.Sleep(time.Millisecond * 990)
		return nil
	})
	assert.Nil(t, err)

	err = xprocess.Timeout(time.Second, func(ctx context.Context) error {
		time.Sleep(time.Second + time.Millisecond*10)
		return nil
	})
	assert.NotNil(t, err)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTimeout = xerror.New("timeout")

Functions

func Go

func Go(fn func(ctx context.Context)) context.CancelFunc

Go 启动一个goroutine

func GoLoop

func GoLoop(fn func(ctx context.Context)) context.CancelFunc

GoLoop 启动一个goroutine loop 是为了替换 `go func() {for{ }}()` 这类的代码

func NewGroup

func NewGroup(opts ...GroupOption) *group

NewGroup 创建一个group对象, 可以带上默认的Context

func Stack

func Stack() string

Stack 获取正在运行的goroutine的stack和数量

func Timeout added in v0.0.3

func Timeout(dur time.Duration, fn func(ctx context.Context) error) error

Timeout 执行超时函数, 超时后, 函数自动退出

Types

type Group added in v0.0.3

type Group = group

type GroupOption added in v0.0.8

type GroupOption func(*group)

func WithConcurrency added in v0.0.8

func WithConcurrency(c uint32) GroupOption

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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