Skip to content

guoquanwei/alloter

Repository files navigation

Introduction

GoDoc

Alloter is a goroutine's concurrent toolkit to help execute functions concurrently in an efficient and safe way.

It was inspired by a Node.js package's function, bluebird .map()

  • It supports concurrency limits.
  • It supports recovery goroutine's panic.
  • It supports specifying the overall timeout to avoid blocking.
  • It supports the use of goroutines pool(invoke ants/v2).
  • It supports context passing; listen ctx.Done(), will return.
  • It supports ending other tasks when an error occurs.

init Alloter

// simple concurrency
func NewAlloter() *Alloter

// concurrency control
func NewCtrlAlloter(workerNum int) *Alloter

// goroutines pool from ants/v2
func NewPooledAlloter(workerNum int) *Alloter

exec tasks

type Task func() error

func (c *Alloter) Exec(tasks []Task) error

func (c *Alloter) ExecWithContext(ctx context.Context, tasks []Task) error

Demo!!!

package main

import (
	"github.com/guoquanwei/alloter"
	"sync"
)

func (that *Controller) TestGoRunLock(ctx echo.Context) {
	userIds := []string{
		"uuid_1",
		"uuid_2",
	}
	var tasks []alloter.Task
	var users []third_parts.User
	mux := sync.Mutex{}
	for _, uid := range userIds {
		func(userId string) {
			tasks = append(tasks, func() error {
				user, resErr := third_parts.GetUserById(userId)
				if resErr != nil {
					return resErr
				}
				mux.Lock()
				users = append(users, user)
				mux.Unlock()
				return nil
			})
		}(uid)
	}
	p := alloter.NewCtrlAlloter(1)
	err = p.ExecWithContext(ctx.Request().Context(), tasks)
	if err != nil {
		ctx.JSON(500, err.Error())
		return
	}
	ctx.JSON(200, users)
	return
}

About

Alloter is a goroutines concurrent toolkit.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy