项目作者: Jeffail

项目描述 :
A goroutine pool for Go
高级语言: Go
项目地址: git://github.com/Jeffail/tunny.git
创建时间: 2014-04-02T16:14:58Z
项目社区:https://github.com/Jeffail/tunny

开源协议:MIT License

下载


Tunny

godoc for Jeffail/tunny
goreportcard for Jeffail/tunny

Tunny is a Golang library for spawning and managing a goroutine pool, allowing
you to limit work coming from any number of goroutines with a synchronous API.

A fixed goroutine pool is helpful when you have work coming from an arbitrary
number of asynchronous sources, but a limited capacity for parallel processing.
For example, when processing jobs from HTTP requests that are CPU heavy you can
create a pool with a size that matches your CPU count.

Install

  1. go get github.com/Jeffail/tunny

Or, using dep:

  1. dep ensure -add github.com/Jeffail/tunny

Use

For most cases your heavy work can be expressed in a simple func(), where you
can use NewFunc. Let’s see how this looks using our HTTP requests to CPU count
example:

  1. package main
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "runtime"
  6. "github.com/Jeffail/tunny"
  7. )
  8. func main() {
  9. numCPUs := runtime.NumCPU()
  10. pool := tunny.NewFunc(numCPUs, func(payload interface{}) interface{} {
  11. var result []byte
  12. // TODO: Something CPU heavy with payload
  13. return result
  14. })
  15. defer pool.Close()
  16. http.HandleFunc("/work", func(w http.ResponseWriter, r *http.Request) {
  17. input, err := ioutil.ReadAll(r.Body)
  18. if err != nil {
  19. http.Error(w, "Internal error", http.StatusInternalServerError)
  20. }
  21. defer r.Body.Close()
  22. // Funnel this work into our pool. This call is synchronous and will
  23. // block until the job is completed.
  24. result := pool.Process(input)
  25. w.Write(result.([]byte))
  26. })
  27. http.ListenAndServe(":8080", nil)
  28. }

Tunny also supports timeouts. You can replace the Process call above to the
following:

  1. result, err := pool.ProcessTimed(input, time.Second*5)
  2. if err == tunny.ErrJobTimedOut {
  3. http.Error(w, "Request timed out", http.StatusRequestTimeout)
  4. }

You can also use the context from the request (or any other context) to handle timeouts and deadlines. Simply replace the Process call to the following:

  1. result, err := pool.ProcessCtx(r.Context(), input)
  2. if err == context.DeadlineExceeded {
  3. http.Error(w, "Request timed out", http.StatusRequestTimeout)
  4. }

Changing Pool Size

The size of a Tunny pool can be changed at any time with SetSize(int):

  1. pool.SetSize(10) // 10 goroutines
  2. pool.SetSize(100) // 100 goroutines

This is safe to perform from any goroutine even if others are still processing.

Goroutines With State

Sometimes each goroutine within a Tunny pool will require its own managed state.
In this case you should implement tunny.Worker, which includes
calls for terminating, interrupting (in case a job times out and is no longer
needed) and blocking the next job allocation until a condition is met.

When creating a pool using Worker types you will need to provide a constructor
function for spawning your custom implementation:

  1. pool := tunny.New(poolSize, func() Worker {
  2. // TODO: Any per-goroutine state allocation here.
  3. return newCustomWorker()
  4. })

This allows Tunny to create and destroy Worker types cleanly when the pool
size is changed.

Ordering

Backlogged jobs are not guaranteed to be processed in order. Due to the current
implementation of channels and select blocks a stack of backlogged jobs will be
processed as a FIFO queue. However, this behaviour is not part of the spec and
should not be relied upon.