workerpool

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2018 License: MIT Imports: 3 Imported by: 0

README

workerpool

CircleCI codecov API Reference Go Report Card license

A Implementation of a Worker Pool Capable of Coordinating Routines in Golang

Overview

This is project motivated by github gist of Mr. rodaine.

Requirement

Installation

go get -u -v github.com/sammy00/workerpool

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Action

type Action interface {
	// Execute performs the work of an Action. This method should make a best
	// effort to be cancelled if the provided ctx is cancelled.
	Execute(ctx context.Context) error
}

An Action performs a single arbitrary task.

type ActionFunc

type ActionFunc func(context.Context) error

ActionFunc permits using a standalone function as an Action.

func (ActionFunc) Execute

func (fn ActionFunc) Execute(ctx context.Context) error

Execute satisfies the Action interface, delegating the call to the underlying function.

type Executor

type Executor interface {
	Close() error
	// Execute performs all provided actions by calling their Execute method.
	// This method should make a best-effort to cancel outstanding actions if the
	// provided ctx is cancelled.
	//Execute(ctx context.Context, actions []Action) error
	Execute(ctx context.Context, actions ...Action) error
}

An Executor performs a set of Actions. It is up to the implementing type to define the concurrency and open/closed failure behavior of the actions.

func Pool

func Pool(n int) Executor

Pool creates an Executor backed by a concurrent worker pool. Up to n Actions can be in-flight simultaneously; if n is less than or equal to zero, runtime.NumCPU is used. The done channel should be closed to release resources held by the Executor. func Pool(n int, done <-chan struct{}) Executor { func Pool(n int) (Executor, context.CancelFunc) {

Example
package main

import (
	"context"
	"fmt"

	"github.com/sammy00/workerpool"
)

func SayHello(ctx context.Context) error {
	fmt.Println("hello")
	return nil
}

func SayWorld(ctx context.Context) error {
	fmt.Println("world")
	return nil
}

func main() {
	//pool, cancel := workerpool.Pool(2)
	//defer cancel()
	pool := workerpool.Pool(2)
	defer pool.Close()

	ctx := context.TODO()
	actions := []workerpool.Action{
		workerpool.ActionFunc(SayHello),
		workerpool.ActionFunc(SayWorld),
		workerpool.ActionFunc(SayWorld),
		workerpool.ActionFunc(SayHello),
	}

	if err := pool.Execute(ctx, actions...); nil != err {
		fmt.Println(err)
		return
	}

}
Output:

hello
world
world
hello

Jump to

Keyboard shortcuts

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