-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.go
53 lines (46 loc) · 963 Bytes
/
io.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"bufio"
"io"
"os"
"sync"
"time"
)
// last modified 2024-01-10.0945
// file reader
func startReader(file *os.File, workChan chan<- []byte) error {
bufferSize := 10 * 1024 * 1024 // 10MB read buffer
reader := bufio.NewReaderSize(file, bufferSize)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
break // end of file
}
return err // return error
}
workChan <- line
}
close(workChan)
return nil
}
// output writer
func startWriter(resultsChan <-chan []byte, wg *sync.WaitGroup) {
defer wg.Done()
outputBuffer := bufio.NewWriterSize(os.Stdout, 1*1024*1024) // 1MB write buffer
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case resultBytes, ok := <-resultsChan:
if !ok {
outputBuffer.Flush()
return
}
outputBuffer.Write(resultBytes)
case <-ticker.C:
// flush the buffer every ticker
outputBuffer.Flush()
}
}
}