-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_1.go
144 lines (108 loc) · 1.98 KB
/
main_1.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
/*
import (
"fmt"
"sync"
"time"
)
func process(val int, wg *sync.WaitGroup) {
fmt.Println("started processing", val)
time.Sleep(2 * time.Second)
fmt.Println("ended processing", val)
wg.Done()
}
func main() {
total := 3
var wg sync.WaitGroup
for i := 0; i < total; i++ {
wg.Add(1)
go process(i, &wg)
}
wg.Wait()
fmt.Println("All go routines are finished")
}*/
/*func producer(ch chan int) {
for i := 0; i < 10; i++ {
ch <- i
fmt.Println("wrote ", i, " into the channel")
}
close(ch)
}
func main() {
ch := make(chan int, 10)
go producer(ch)
time.Sleep(2 * time.Second)
for v := range ch {
fmt.Println("read val", v, "from the channel")
time.Sleep(2 * time.Second)
}
}*/
type Job struct {
id int
number int
}
type Result struct {
job Job
sumOfDigits int
}
var jobs = make(chan Job, 10)
var results = make(chan Result, 10)
func digits(number int) int {
var sum int
for number != 0 {
digit := number % 10
sum = sum + digit
number /= 10
}
time.Sleep(2 * time.Second)
return sum
}
func worker(wg *sync.WaitGroup) {
for job := range jobs {
output := Result{job, digits(job.number)}
results <- output
}
wg.Done()
}
func createWorkerPool(workersCount int) {
var wg sync.WaitGroup
for i := 0; i < workersCount; i++ {
wg.Add(1)
go worker(&wg)
}
wg.Wait()
close(results)
}
func allocate(noOfJobs int) {
for i := 0; i < noOfJobs; i++ {
number := rand.Intn(999)
job := Job{i, number}
jobs <- job
}
close(jobs)
}
func result(done chan bool) {
for result := range results {
fmt.Printf("Job id %d, input %d, sum of digits %d\n", result.job.id, result.job.number, result.sumOfDigits)
}
done <- true
}
func main_1() {
start := time.Now()
jobsCount := 100
go allocate(jobsCount)
done := make(chan bool)
go result(done)
noOfWorkers := 50
createWorkerPool(noOfWorkers)
<-done
end := time.Now()
diff := end.Sub(start)
fmt.Println("Total time taken", diff)
}