parallel

package module
v0.0.0-...-335c4cf Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2022 License: MIT Imports: 5 Imported by: 0

README

parallel

some commonly used go concurrency models

concurrent requests with timeout capability

how to use

tasks := make([]TaskFunc, 0, testSize)
tasks = append(tasks, func (ctx context.Context, i int) (Result, error) {
    // do your things, like rpc call
})
wo := New(tasks)
result, err := wo.ParallelingWithTimeout(context.Background(), 5*time.Second)

explain

there are 3 version about ParallelingWithTimeout function

  • ParallelingWithTimeout original concurrency models
  • ParallelingWithTimeoutV2 use WaitGroup secure synchronization about goroutines
  • ParallelingWithTimeoutV3 use errgroup streamline the code

v3 is recommended

design principle

  1. If you want implement a function with timeout, do not use sync.WaitGroup.Wait on the main goroutine, because the function you want to implement needs to exit during timeout, If the main goroutine is synchronized using wait, main goroutine can not quit midway.
  2. When you use channel, try to make sure, who send the data, who close it. If you make sure there are no one to send data, you can close it anywhere.
  3. In fact, the close function is a very useful method, it can be used to tell multiple coroutines to end blocking, like the cancelCtx do.
  4. Please ensure that all new gorutine can be exited, unless you have a special purpose

license

MIT License

Documentation

Overview

Package parallel use ParallelingWithTimeout to query, and set the timeout

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTimeout = errors.New("service is timeout")
)

Functions

func DoWithTimeout

func DoWithTimeout(ctx context.Context, f func() error, timeout time.Duration) (err error)

Types

type Result

type Result any

type TaskFunc

type TaskFunc func(ctx context.Context, i int) (Result, error)

type Worker

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

func New

func New(tasks []TaskFunc) *Worker

func (*Worker) Add

func (wo *Worker) Add(task TaskFunc) *Worker

func (*Worker) ParallelingWithTimeout

func (wo *Worker) ParallelingWithTimeout(ctx context.Context, timeout time.Duration) (res []Result, err error)

ParallelingWithTimeout do the query

func (*Worker) ParallelingWithTimeoutV2

func (wo *Worker) ParallelingWithTimeoutV2(ctx context.Context, timeout time.Duration) (res []Result, err error)

ParallelingWithTimeoutV2 do the query

func (*Worker) ParallelingWithTimeoutV3

func (wo *Worker) ParallelingWithTimeoutV3(ctx context.Context, timeout time.Duration) (res []Result, err error)

ParallelingWithTimeoutV3 do the query

Jump to

Keyboard shortcuts

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