-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmapreduce.go
More file actions
58 lines (48 loc) · 1.19 KB
/
mapreduce.go
File metadata and controls
58 lines (48 loc) · 1.19 KB
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
// Package mapreduce provides a simple abstraction for the general Map/Reduce
// pattern.
package mapreduce
import (
"sync"
)
// In order to utilize this package you must create a struct that implements
// the following interface.
type MapReduce interface {
Map(in chan interface{}, out chan interface{})
Reduce(in chan interface{}) interface{}
}
// Configuration used by the Map Reducer.
type Configuration struct {
MapperCount int
InChan chan interface{}
OutChan chan interface{}
}
// NewMapReduceConfig returns a MapReduce Configuration struct with sensible
// defaults.
func NewMapReduceConfig() *Configuration {
inChan := make(chan interface{})
outChan := make(chan interface{})
return &Configuration{
MapperCount: 1,
InChan: inChan,
OutChan: outChan,
}
}
// Run executes the MapReduce process.
func Run(mr MapReduce, c *Configuration) (interface{}, error) {
var wg sync.WaitGroup
// Map
wg.Add(c.MapperCount)
for i := 0; i < c.MapperCount; i++ {
go func(wg *sync.WaitGroup) {
mr.Map(c.InChan, c.OutChan)
wg.Done()
}(&wg)
}
go func(w *sync.WaitGroup) {
w.Wait()
close(c.OutChan)
}(&wg)
// Reduce
res := mr.Reduce(c.OutChan)
return res, nil
}