| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
// ErrScheduleTimeout returned by Pool to indicate that there no free |
| 9 |
// goroutines during some period of time. |
| 10 |
var ErrScheduleTimeout = fmt.Errorf("schedule error: timed out") |
| 11 |
|
| 12 |
// Pool contains logic of goroutine reuse. |
| 13 |
type Pool struct { |
| 14 |
sem chan struct{} |
| 15 |
work chan func() |
| 16 |
} |
| 17 |
|
| 18 |
// NewPool creates new goroutine pool with given size. It also creates a work |
| 19 |
// queue of given size. Finally, it spawns given amount of goroutines |
| 20 |
// immediately. |
| 21 |
func NewPool(size, queue, spawn int) *Pool { |
| 22 |
if spawn <= 0 && queue > 0 { |
| 23 |
panic("dead queue configuration detected") |
| 24 |
} |
| 25 |
if spawn > size { |
| 26 |
panic("spawn > workers") |
| 27 |
} |
| 28 |
p := &Pool{ |
| 29 |
sem: make(chan struct{}, size), |
| 30 |
work: make(chan func(), queue), |
| 31 |
} |
| 32 |
for i := 0; i < spawn; i++ { |
| 33 |
p.sem <- struct{}{} |
| 34 |
go p.worker(func() {}) |
| 35 |
} |
| 36 |
|
| 37 |
return p |
| 38 |
} |
| 39 |
|
| 40 |
// Schedule schedules task to be executed over pool's workers. |
| 41 |
func (p *Pool) Schedule(task func()) { |
| 42 |
p.schedule(task, nil) |
| 43 |
} |
| 44 |
|
| 45 |
// ScheduleTimeout schedules task to be executed over pool's workers. |
| 46 |
// It returns ErrScheduleTimeout when no free workers met during given timeout. |
| 47 |
func (p *Pool) ScheduleTimeout(timeout time.Duration, task func()) error { |
| 48 |
return p.schedule(task, time.After(timeout)) |
| 49 |
} |
| 50 |
|
| 51 |
func (p *Pool) schedule(task func(), timeout <-chan time.Time) error { |
| 52 |
select { |
| 53 |
case <-timeout: |
| 54 |
return ErrScheduleTimeout |
| 55 |
case p.work <- task: |
| 56 |
return nil |
| 57 |
case p.sem <- struct{}{}: |
| 58 |
go p.worker(task) |
| 59 |
return nil |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
func (p *Pool) worker(task func()) { |
| 64 |
defer func() { <-p.sem }() |
| 65 |
|
| 66 |
task() |
| 67 |
|
| 68 |
for task := range p.work { |
| 69 |
task() |
| 70 |
} |
| 71 |
} |