有几种可能性,但我猜你的意思是“高效地”?
总体思路是将文本拆分成可管理的块,将这些块堆叠到队列中,并让多个消费者处理这些块。
对我来说,这看起来像一个典型的Map/Reduce应用程序:
_ Worker_
/ \
/ \
Splitter--- Worker ---Aggregator
\ /
\_ Worker _/
/*
The problem: Write a program that reads text from
standard-input, and returns (prints) the total
number of distinct words found in the text.
C versus C++, Jakob Østergaard, February 24th, 2004
http://unthought.net/c++/c_vs_c++.html
*/
package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
func main() {
rdr := bufio.NewReader(os.Stdin)
words := make(map[string]bool, 1024*1024)
word := make([]int, 0, 256)
for {
r, n, _ := rdr.ReadRune()
if unicode.IsSpace(r) || n == 0 {
if len(word) > 0 {
words[string(word)] = true
word = word[:0]
}
if n == 0 {
break
}
} else {
word = append(word, r)
}
}
fmt.Println(len(words))
}
在这个问题以及其他大多数问题中,仅仅添加“并行编程”这个短语是很幼稚的,并期望有所神奇的改进。从流中按顺序读取输入和执行微不足道的计算并不提供任何显著的并行计算机会。