{"modulePath":"github.com/EternizedLab/utils","version":"v1.0.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package routine\n\n## Functions\n\n```go\nfunc ConcurrentTasksWithCtxTimeout(baseCtx context.Context, numWorker int, tasks []*ConcurrentTask) error\n```\nConcurrentTasksWithCtxTimeout process task functions concurrently\n\n```go\nfunc Map(size, numWorker int, f func(i int) error) error\n```\nMap is a helper function to parallel operate on slice. Example usage: \\`\\`\\`\n\n\titemIDs := []int{1, 2, 3}\n\titems := make([]*Item, len(itemIDs))\n\troutine.Map(len(items), 10, func(i int) {\n\t  items[i] = getItemByID(itemIDs[i])\n\t})\n\n\\`\\`\\`\n\n```go\nfunc MapWithContext(ctx context.Context, size, numWorker int, f func(ctx context.Context, i int) error) error\n```\n\n```go\nfunc MapWithCtxTimeout(baseCtx context.Context, size, numWorker int, timeout time.Duration, f func(ctx context.Context, i int) error) error\n```\n\n```go\nfunc MapWithTimeout(size, numWorker int, timeout time.Duration, f func(ctx context.Context, i int) error) error\n```\nMapWithTimeout is the same as Map, except each function need to be executed within timeout. Important reminder to handle the context provided: It is better to check the \\`ctx.Err() == nil\\` before any write operation, because the function may be canceled at any momement, and the underlying resource refering may have already been discarded.\n\n```go\nfunc ProcessStream[T any, K comparable](ctx context.Context, numWorker int, inputChan \u003c-chan T, outputChan chan\u003c- K, fn ProcessFunc[T, K]) error\n```\nProcessStream provides a way to process stream data in multiple go routine, while preserving the ordinal order unchanged. The invoker just need to provide a process func to handle the concrete processing logic. If the func returns nil value or non-nil error, the value will be ignored. The parameter \\`inputChan\\` and \\`outputChan\\` accepts any kind of channels. Notice: The process func should honor the input context, otherwise it will result in routine leaking.\n\n```go\nfunc RunTasks(ctx context.Context, fs ...func(ctx context.Context) error) (err error)\n```\n\n```go\nfunc Select[T any](ctx context.Context, src []\u003c-chan T) \u003c-chan *ValueType[T]\n```\nSelect function helps caller reading data from multiple channel on limit time, and caller can know result came from which channel by mapping  ValueType.Index to input channels Example:\n\n\tsources := make([]chan int32, 10)\n\toutput := routine.Select(ctx, sources)\n\tfor v := range output {\n\t fmt.Println(v.Index, v.Value)\n\t}\n\n```go\nfunc SuggestNum(i int) int\n```\nSuggestNum 基于当前运行条件，适合并发的 goroutine 数量. 目前的评估算法是：需要处理的任务数量与 CPU 核数\\*2 相比较，选择较小者.\n\n```go\nfunc WithSignal(ctx context.Context) context.Context\n```\n\n## Types\n\n```go\ntype BulkEmitter[T, K any] struct {\n\t// contains filtered or unexported fields\n}\n```\nBulkEmitter is used to stack multiple requests to do batch requests. It's mostly used to invoke batch API of database or service.\n\n```go\nfunc NewBulkEmitter[T, K any](handler BulkEmitterHandler[T, K], opts ...BulkEmitterOption[T, K]) *BulkEmitter[T, K]\n```\nNewBulkEmitter returns a BulkEmitter object.\n\n```go\nfunc (be *BulkEmitter[T, K]) Close()\n```\nClose release the resource used by emitter. Panic when called more than once.\n\n```go\nfunc (be *BulkEmitter[T, K]) CloseAndWait()\n```\nCloseAndWait release the resource used by emitter. Panic when called more than once. Wait until the the emitter finishes.\n\n```go\nfunc (be *BulkEmitter[T, K]) Commit(ctx context.Context, key string, request T, handler func(reply K, err error)) error\n```\nCommit submits the individual request. Rather than waiting until the whole action is completed, it returns intermediately after the request has been accepted by the bulk emitter, with the contraint of the processor limit. Key will be used to identify and deduplicate the requests. The response will be handled in argument \\`handler\\` after the reply has returned. If the handler is nil, the reply and error will be ignored.\n\n```go\nfunc (be *BulkEmitter[T, K]) Do(ctx context.Context, key string, request T) (K, error)\n```\nDo submits the individual request. It will wait until the action is completed. Key will be used to identify and deduplicate the requests. The response will be the same for the request with same key.\n\nWARNING: It's dangerous to invoke the Do() method in an unconstraint go routine, where routine leaking is inevitable. When in such case, it's strongly suggested to use Commit() instead of Do().\n\n```go\nfunc (be *BulkEmitter[T, K]) Run(ctx context.Context) error\n```\nRun starts emitter looping logic. Must be called once.\n\n```go\ntype BulkEmitterHandler[T, K any] func(requests map[string]T) (replies map[string]K, err error)\n```\nBulkEmitterHandler is callback to invoke when a batch of requests are grouped together, and desires actual action.\n\n```go\ntype BulkEmitterOption[T, K any] func(be *BulkEmitter[T, K])\n```\nBulkEmitterOption helps set variables of BulkEmitter.\n\n```go\nfunc WithInterval[T, K any](interval time.Duration) BulkEmitterOption[T, K]\n```\nWithInterval sets emitting interval.\n\n```go\nfunc WithMaxSize[T, K any](size int) BulkEmitterOption[T, K]\n```\nWithMaxSize sets max size of a bulk.\n\n```go\nfunc WithWorker[T, K any](num int) BulkEmitterOption[T, K]\n```\nWithWorker sets the concurrent worker to coexists.\n\n```go\ntype BulkError map[string]error\n```\nBulkError can be returned in \\`BulkEmitterHandler\\` to indicate error for each individual response.\n\n```go\nfunc (e BulkError) Error() string\n```\nError returns error msg.\n\n```go\ntype ConcurrentTask struct {\n\tF                 func(ctx context.Context) error\n\tWithBlockSignal   bool\n\tIgnoreBlockSignal bool\n\tTimeout           time.Duration\n}\n```\nConcurrentTask define functions as tasks. F指的是具体的可以并行执行的任务； WithBlockSignal表示当前任务如果出错，是否发出一个block信号，去尝试阻止任务集群内更多的任务继续执行。（已经开始的任务要看任务内部是否处理相关信号。） IgnoreBlockSignal表示当前任务不关心block信号，仅会考虑超时的影响 Timeout表示每个任务自己的超时时间\n\n```go\ntype ConcurrentTaskRunner struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewConcurrentTaskRunner(ctx context.Context, opts ...RunnerOption) *ConcurrentTaskRunner\n```\n\n```go\nfunc (c *ConcurrentTaskRunner) AddTasks(fs ...func(ctx context.Context) error) *ConcurrentTaskRunner\n```\n\n```go\nfunc (c *ConcurrentTaskRunner) Run() (err error)\n```\n\n```go\ntype ProcessFunc[T any, K comparable] func(context.Context, T) (K, error)\n```\n\n```go\ntype RunnerOption func(c *ConcurrentTaskRunner)\n```\n\n```go\nfunc WithNumOfWorker(numOfWorker int) RunnerOption\n```\n\n```go\nfunc WithTimeout(duration time.Duration) RunnerOption\n```\n\n```go\ntype Safe struct {\n\t// contains filtered or unexported fields\n}\n```\nSafe aids user access fields in struct in concurrent way. The returned error from given function will be passthrough. Suggested usage: \\`\\`\\`\n\n\ttype MyClass struct {\n\t  routine.Safe\n\t  ... Other fields\n\t}\n\n\terr := myclass.View(func() error {\n\t  got := myclass.somefield\n\n\t  ... DO NOT invoke other method of the same instance,\n\t      otherwise it may occurs deadlock by accident.\n\t})\n\n\\`\\`\\`\n\n```go\nfunc (s *Safe) Update(fn func() error) error\n```\n\n```go\nfunc (s *Safe) View(fn func() error) error\n```\n\n```go\ntype ValueType[T any] struct {\n\tValue T\n\tIndex int\n}\n```\n\n","path":"github.com/EternizedLab/utils/routine","name":"routine","synopsis":"","isRedistributable":true}
