Last active
January 12, 2019 02:05
-
-
Save xemoe/28dafdfdff23315b814b1d1982600882 to your computer and use it in GitHub Desktop.
golang concurrent sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
func main() { | |
process() | |
} | |
func process() { | |
jobs := make(chan string, 5) | |
results := make(chan string, 5) | |
// | |
// create jobs | |
// | |
wg := new(sync.WaitGroup) | |
for w := 1; w <= 3; w++ { | |
wg.Add(1) | |
go mapping(jobs, results, wg) | |
} | |
feed(jobs) | |
go func() { | |
wg.Wait() | |
close(results) | |
}() | |
sum := reduce(results) | |
fmt.Println(sum) | |
} | |
func feed(jobs chan<- string) { | |
records := []string{"foo", "bar", "exp", "foo", "exp", "fish", "dog", "cat", "tiger"} | |
for i := 0; i < len(records); i++ { | |
jobs <- records[i] | |
} | |
close(jobs) | |
} | |
func mapping(jobs <-chan string, results chan<- string, wg *sync.WaitGroup) { | |
defer wg.Done() | |
for j := range jobs { | |
results <- j | |
} | |
} | |
func reduce(results <-chan string) map[string]int { | |
sum := map[string]int{} | |
for v := range results { | |
sum[v] += 1 | |
} | |
return sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment