workerpool

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2021 License: GPL-3.0 Imports: 1 Imported by: 0

Documentation

Overview

Example
package main

import (
	"fmt"

	wp "gitlab.com/mipimipi/go-utils/workerpool"
)

func main() {
	// fibN is the result structure for Fibonacci calculation: Mapping of n to the
	// n-th Fibonacci number
	type fibN struct {
		n   int
		fib int
	}

	// fibonacci calculates the n-th Fibonacci number
	var fibonacci func(int) fibN
	fibonacci = func(n int) fibN {
		if n < 2 {
			return fibN{n: n, fib: n}
		}
		return fibN{n: n, fib: fibonacci(n-1).fib + fibonacci(n-2).fib}
	}

	// create worker pool with 10 workers
	pl := wp.NewPool(10)

	// submit tasks to worker pool. To not have to wait, that's done in a Go
	// routine
	go func() {
		for n := 0; n < 100; n++ {
			pl.In <- wp.Task{
				Name: "fibonacci",
				F: func(i interface{}) interface{} {
					return fibonacci(i.(int))
				},
				In: n}
		}
		close(pl.In)
	}()

	// retrieve results from worker pool
	for res := range pl.Out {
		fmt.Printf("%3d-th Fibonacci Number = %d\n", res.Out.(fibN).n, res.Out.(fibN).fib)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Pool

type Pool struct {
	In  chan Task   // input channel
	Out chan Result // output channel
	// contains filtered or unexported fields
}

Pool represents a worker pool. The pool mainly consists of channels that let it communicate with the outside (submitting tasks, receiving results etc.).

func NewPool

func NewPool(numWorkers int) *Pool

NewPool creates a new worker pool with numWorkers number of go routines

func (*Pool) Stop

func (pl *Pool) Stop()

Stop stops processing

func (*Pool) Wait

func (pl *Pool) Wait()

Wait until pool finished

type Result

type Result struct {
	Name string      // name of task
	Out  interface{} // output data of task
}

Result represents the result of a task

type Task

type Task struct {
	Name string                        // name of task
	F    func(interface{}) interface{} // function that implements the task
	In   interface{}                   // input data of task
}

Task represents a task that shall be executed by the workers

Jump to

Keyboard shortcuts

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