pool

package module
v0.0.0-...-dc1366c Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2021 License: Apache-2.0 Imports: 3 Imported by: 0

README

pool

一个类似python gevent.Pool的协程池

Example

package main

import (
	"fmt"
	"time"

	"github.com/greyh4t/pool"
)

func work(args ...interface{}) interface{} {
	fmt.Println(args...)
	time.Sleep(time.Second)
	return fmt.Sprintf("result:%v", args[0])
}

func example1() {
	p := pool.New(2)
	taskCount := 10

	var jobs []*pool.Job
	for i := 0; i < taskCount; i++ {
		job := p.Spawn(work, i)
		jobs = append(jobs, job)
	}

	// job.Get会自动等待任务结束
	for _, job := range jobs {
		result := job.Get()
		fmt.Println(result)
	}
}

func example2() {
	p := pool.New(2)
	taskCount := 10

	var jobs []*pool.Job
	for i := 0; i < taskCount; i++ {
		job := p.Spawn(work, i)
		jobs = append(jobs, job)
	}

	// 如果不需要获取结果,可以直接调用JoinAll等待任务结束
	p.JoinAll(jobs)
}

func example3() {
	p := pool.New(2)
	args := []interface{}{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

	// 调用Map直接获取所有参数的执行结果
	result := p.Map(work, args)

	fmt.Println(result)
}

func main() {
	fmt.Println("<--example1-->")
	example1()
	fmt.Println("<--example2-->")
	example2()
	fmt.Println("<--example3-->")
	example3()
}

Installation

go get github.com/greyh4t/pool

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Job

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

func (*Job) Get

func (r *Job) Get() interface{}

Get wait and return the job result

func (*Job) Join

func (r *Job) Join()

Join wait job finished

type Pool

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

func New

func New(size int64) *Pool

New make a new Pool

func (*Pool) GetSize

func (p *Pool) GetSize() int64

GetSize get the pool size

func (*Pool) JoinAll

func (p *Pool) JoinAll(jobs []*Job)

JoinAll wait all job finished

func (*Pool) Map

func (p *Pool) Map(f WorkFunc, args []interface{}) []interface{}

Map do multiple jobs and return results in order

func (*Pool) SetSize

func (p *Pool) SetSize(size int64)

SetSize change the pool size

func (*Pool) Spawn

func (p *Pool) Spawn(f WorkFunc, args ...interface{}) *Job

Spawn do a job in pool

type WorkFunc

type WorkFunc func(arg ...interface{}) interface{}

WorkFunc is the worker function user define

Jump to

Keyboard shortcuts

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