forked from PacktPublishing/Mastering-Go-Second-Edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkerPool.go
88 lines (75 loc) · 1.29 KB
/
workerPool.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"fmt"
"os"
"strconv"
"sync"
"time"
)
type Client struct {
id int
integer int
}
type Data struct {
job Client
square int
}
var (
size = 10
clients = make(chan Client, size)
data = make(chan Data, size)
)
func worker(w *sync.WaitGroup) {
for c := range clients {
square := c.integer * c.integer
output := Data{c, square}
data <- output
time.Sleep(time.Second)
}
w.Done()
}
func makeWP(n int) {
var w sync.WaitGroup
for i := 0; i < n; i++ {
w.Add(1)
go worker(&w)
}
w.Wait()
close(data)
}
func create(n int) {
for i := 0; i < n; i++ {
c := Client{i, i}
clients <- c
}
close(clients)
}
func main() {
fmt.Println("Capacity of clients:", cap(clients))
fmt.Println("Capacity of data:", cap(data))
if len(os.Args) != 3 {
fmt.Println("Need #jobs and #workers!")
return
}
nJobs, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err)
return
}
nWorkers, err := strconv.Atoi(os.Args[2])
if err != nil {
fmt.Println(err)
return
}
go create(nJobs)
finished := make(chan interface{})
go func() {
for d := range data {
fmt.Printf("Client ID: %d\tint: ", d.job.id)
fmt.Printf("%d\tsquare: %d\n", d.job.integer, d.square)
}
finished <- true
}()
makeWP(nWorkers)
fmt.Printf(": %v\n", <-finished)
}