go>> pool>> 返回
项目作者: corpix

项目描述 :
Simplest go routine pool ever
高级语言: Go
项目地址: git://github.com/corpix/pool.git
创建时间: 2017-05-29T11:25:29Z
项目社区:https://github.com/corpix/pool

开源协议:MIT License

下载


pool

Build Status

Simplest goroutine pool ever.

Simple example

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "github.com/corpix/pool"
  8. )
  9. func main() {
  10. p := pool.New(10, 10)
  11. defer p.Close()
  12. w := &sync.WaitGroup{}
  13. tasks := 10
  14. sleep := 1 * time.Second
  15. for n := 0; n < tasks; n++ {
  16. w.Add(1)
  17. p.Push(pool.NewWork(
  18. context.Background(),
  19. func(n int) pool.Executor {
  20. return func(ctx context.Context) {
  21. select {
  22. case <-ctx.Done():
  23. default:
  24. time.Sleep(sleep)
  25. fmt.Printf("Finished work '%d'\n", n)
  26. }
  27. w.Done()
  28. }
  29. }(n),
  30. ))
  31. }
  32. w.Wait()
  33. }

Output:

Results may differ on your machine, order is not guarantied.

  1. $ go run ./example/simple/simple.go
  2. Finished work '6'
  3. Finished work '9'
  4. Finished work '7'
  5. Finished work '5'
  6. Finished work '4'
  7. Finished work '8'
  8. Finished work '2'
  9. Finished work '0'
  10. Finished work '3'
  11. Finished work '1'

Example with work result

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. "github.com/corpix/pool"
  7. )
  8. func main() {
  9. p := pool.New(10, 10)
  10. defer p.Close()
  11. w := &sync.WaitGroup{}
  12. tasks := 10
  13. results := make(chan *pool.Result)
  14. defer close(results)
  15. for n := 0; n < tasks; n++ {
  16. w.Add(1)
  17. p.Push(pool.NewWorkWithResult(
  18. context.Background(),
  19. results,
  20. func(n int) pool.ExecutorWithResult {
  21. return func(ctx context.Context) (interface{}, error) {
  22. select {
  23. case <-ctx.Done():
  24. return nil, ctx.Err()
  25. default:
  26. fmt.Printf("Finished work '%d'\n", n)
  27. }
  28. return n, nil
  29. }
  30. }(n),
  31. ))
  32. }
  33. go func() {
  34. // Releasing one worker per iteration
  35. // when using not buffered channels.
  36. for result := range results {
  37. fmt.Printf(
  38. "Received result '%d'\n",
  39. result.Value.(int),
  40. )
  41. w.Done()
  42. }
  43. }()
  44. w.Wait()
  45. }

Output:

Results may differ on your machine, order is not guarantied.

  1. $ go run ./example/with_result/with_result.go
  2. Finished work '0'
  3. Finished work '1'
  4. Received result '0'
  5. Received result '1'
  6. Finished work '2'
  7. Finished work '3'
  8. Received result '2'
  9. Received result '3'
  10. Finished work '4'
  11. Finished work '5'
  12. Received result '4'
  13. Received result '5'
  14. Finished work '6'
  15. Finished work '8'
  16. Received result '6'
  17. Received result '8'
  18. Finished work '9'
  19. Received result '9'
  20. Finished work '7'
  21. Received result '7'