To implement a parallel map-reduce pattern using Goroutines and sync in Golang, you can follow these steps:
import (
"sync"
)
func mapper(inputItem int) int {
// Perform mapping operation on inputItem
// Return the result
}
func reducer(mappedResults []int) int {
// Perform reducing operation on mappedResults
// Return the final result
}
func parallelMapReduce(data []int, mapperFunc func(int) int, reducerFunc func([]int) int) int {
// Create a WaitGroup to wait for goroutines to complete
var wg sync.WaitGroup
// Create a channel to receive mapped results
mappedResultsChan := make(chan int, len(data))
// Launch goroutines for the map operation
for _, item := range data {
wg.Add(1)
go func(item int) {
defer wg.Done()
mappedResult := mapperFunc(item)
mappedResultsChan <- mappedResult
}(item)
}
// Close the channel once all goroutines are done
go func() {
wg.Wait()
close(mappedResultsChan)
}()
// Create a slice to store mapped results
mappedResults := make([]int, 0, len(data))
for result := range mappedResultsChan {
mappedResults = append(mappedResults, result)
}
// Perform the reduce operation on mapped results
finalResult := reducerFunc(mappedResults)
return finalResult
}
func main() {
data := []int{1, 2, 3, 4, 5}
finalResult := parallelMapReduce(data, mapper, reducer)
fmt.Println("Final Result:", finalResult)
}
Make sure to replace the mapper
and reducer
functions with your custom logic. This implementation utilizes Goroutines for parallelism and sync package's WaitGroup
and channel for synchronization and communication between Goroutines.