forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (55 loc) · 1.28 KB
/
main.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// This sample program demonstrates how to use the work package
// to use a pool of goroutines to get work done.
package main
import (
"log"
"sync"
"time"
"github.com/ardanlabs/gotraining/topics/concurrency_patterns/task"
)
// names provides a set of names to display.
var names = []string{
"steve",
"bob",
"mary",
"therese",
"jason",
}
// namePrinter provides special support for printing names.
type namePrinter struct {
name string
}
// Work implements the Worker interface.
func (m namePrinter) Work() {
log.Println(m.name)
time.Sleep(3 * time.Second)
}
func main() {
const routines = 10
// Create a task pool.
t := task.New(routines)
var wg sync.WaitGroup
wg.Add(routines * len(names))
for i := 0; i < routines; i++ {
// Iterate over the slice of names.
for _, name := range names {
// Create a namePrinter and provide the
// specific name.
np := namePrinter{
name: name,
}
go func() {
// Submit the task to be worked on. When Do
// returns, we know it is being handled.
t.Do(np)
wg.Done()
}()
}
}
wg.Wait()
// Shutdown the task pool and wait for all existing work
// to be completed.
t.Shutdown()
}