feat: Improve the program execution time by using gorutines

This commit is contained in:
rjianu
2023-07-12 16:56:36 +03:00
parent 209c1b93c6
commit 9f35c4eeeb
3 changed files with 45 additions and 14 deletions

53
main.go
View File

@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"sync"
)
func main() {
@@ -37,25 +38,49 @@ func run(filenames []string, op string, column int, out io.Writer) error {
}
consolidate := make([]float64, 0)
resCh := make(chan []float64)
errCh := make(chan error)
doneCh := make(chan struct{})
wg := sync.WaitGroup{}
for _, fname := range filenames {
f, err := os.Open(fname)
if err != nil {
return fmt.Errorf("cannot open file: %w", err)
}
wg.Add(1)
go func(fname string) {
defer wg.Done()
f, err := os.Open(fname)
if err != nil {
errCh <- fmt.Errorf("cannot open file: %w", err)
return
}
data, err := csv2float(f, column)
if err != nil {
return err
}
data, err := csv2float(f, column)
if err != nil {
errCh <- err
}
if err := f.Close(); err != nil {
return err
}
if err := f.Close(); err != nil {
errCh <- err
}
resCh <- data
}(fname)
consolidate = append(consolidate, data...)
}
_, err := fmt.Fprintln(out, opFunc(consolidate))
return err
go func() {
wg.Wait()
close(doneCh)
}()
for {
select {
case err := <-errCh:
return err
case data := <-resCh:
consolidate = append(consolidate, data...)
case <-doneCh:
_, err := fmt.Fprintln(out, opFunc(consolidate))
return err
}
}
}