私はRead the lines into the work queue
機能の中に「あなたにとってr1-r2有効な番号は何ですか」と判断すべきだと思います。
したがって、valid numbers
のペアがないうちに、現在の行を読み、次の行を1行ずつ読み込む必要があります。あなたが得たら、このペアをworkQueue
チャンネルの中に送り、次のペアを探します。
これは変更にあなたのコードです:
ファイルから読み込んだデータを処理するときに、特に、右の同時解決に飛び込むべきではありません
package main
import (
"bufio"
"log"
"os"
"errors"
)
var concurrency = 100
type Pair struct {
line1 string
line2 string
}
func main() {
// It will be better to receive file-path from somewhere (like args or something like this)
filePath := "/path/to/file.csv"
// This channel has no buffer, so it only accepts input when something is ready
// to take it out. This keeps the reading from getting ahead of the writers.
workQueue := make(chan Pair)
// We need to know when everyone is done so we can exit.
complete := make(chan bool)
// Read the lines into the work queue.
go func() {
file, e := os.Open(filePath)
if e != nil {
log.Fatal(e)
}
// Close when the function returns
defer file.Close()
scanner := bufio.NewScanner(file)
// Get pairs and send them into "workQueue" channel
for {
line1, e := getNextCorrectLine(scanner)
if e != nil {
break
}
line2, e := getNextCorrectLine(scanner)
if e != nil {
break
}
workQueue <- Pair{line1, line2}
}
// Close the channel so everyone reading from it knows we're done.
close(workQueue)
}()
// Now read them all off, concurrently.
for i := 0; i < concurrency; i++ {
go startWorking(workQueue, complete)
}
// Wait for everyone to finish.
for i := 0; i < concurrency; i++ {
<-complete
}
}
func getNextCorrectLine(scanner *bufio.Scanner) (string, error) {
var line string
for scanner.Scan() {
line = scanner.Text()
if isCorrect(line) {
return line, nil
}
}
return "", errors.New("no more lines")
}
func isCorrect(str string) bool {
// Make your validation here
return true
}
func startWorking(pairs <-chan Pair, complete chan<- bool) {
for pair := range pairs {
doTheWork(pair)
}
// Let the main process know we're done.
complete <- true
}
func doTheWork(pair Pair) {
// Do the work with the pair
}
、ファイルからの読み取りなど(またはネットワークから)がボトルネックになることがありあなたのアプリの中で、処理部分を並行させることから何も勝つことはできません。反対に、同時に処理を遅く複雑にするかもしれません。 – icza
はい、しかし、行との作業(githubへのリンクから)は単純な操作ではなく、長い時間がかかる場合、コンカレントソリューションは意味をなさないです。 –