forked from goinaction/code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwork.go
More file actions
48 lines (40 loc) · 870 Bytes
/
work.go
File metadata and controls
48 lines (40 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Example provided with help from Jason Waldrip.
// Package work manages a pool of goroutines to perform work.
package work
import "sync"
// Worker must be implemented by types that want to use
// the work pool.
type Worker interface {
Task()
}
// Pool provides a pool of goroutines that can execute any Worker
// tasks that are submitted.
type Pool struct {
work chan Worker
wg sync.WaitGroup
}
// New creates a new work pool.
func New(maxGoroutines int) *Pool {
p := Pool{
work: make(chan Worker),
}
p.wg.Add(maxGoroutines)
for i := 0; i < maxGoroutines; i++ {
go func() {
for w := range p.work {
w.Task()
}
p.wg.Done()
}()
}
return &p
}
// Run submits work to the pool.
func (p *Pool) Run(w Worker) {
p.work <- w
}
// Shutdown waits for all the goroutines to shutdown.
func (p *Pool) Shutdown() {
close(p.work)
p.wg.Wait()
}