나는 당신이 Read the lines into the work queue
기능 안에 "당신을위한 r1-r2 유효 숫자"라고 판단해야한다고 생각합니다.
그러므로 현재 행을 읽고 valid numbers
쌍이없는 동안 다음 행을 하나씩 읽어야합니다. 가지고 계시면 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에 대한 링크에서)이 단순한 작업이 아니며 오랜 시간이 걸리는 경우 이해가됩니다. –