Just another update
This commit is contained in:
parent
a25938f123
commit
00a190b0a6
6591 changed files with 94363 additions and 23227 deletions
|
|
@ -1,56 +1,54 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"bufio"
|
||||
"io"
|
||||
"os"
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// main, one of two goroutines used, will function as the "reading unit"
|
||||
func main() {
|
||||
// get file open first
|
||||
f, err := os.Open("input.txt")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
lr := bufio.NewReader(f)
|
||||
// get file open first
|
||||
f, err := os.Open("input.txt")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
lr := bufio.NewReader(f)
|
||||
|
||||
// that went ok, now create communication channels,
|
||||
// and start second goroutine as the "printing unit"
|
||||
lines := make(chan string)
|
||||
count := make(chan int)
|
||||
go printer(lines, count)
|
||||
// that went ok, now create communication channels,
|
||||
// and start second goroutine as the "printing unit"
|
||||
lines := make(chan string)
|
||||
count := make(chan int)
|
||||
go printer(lines, count)
|
||||
|
||||
for {
|
||||
line, prefix, err := lr.ReadLine()
|
||||
switch {
|
||||
case err == io.EOF:
|
||||
case err != nil:
|
||||
fmt.Println(err)
|
||||
case prefix:
|
||||
fmt.Println("unexpected long line")
|
||||
default:
|
||||
lines <- string(line)
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
// this represents the request for the printer to send the count
|
||||
close(lines)
|
||||
// wait for the count from the printer, then print it, then exit
|
||||
fmt.Println("Number of lines:", <-count)
|
||||
for {
|
||||
switch line, err := lr.ReadString('\n'); err {
|
||||
case nil:
|
||||
lines <- line
|
||||
continue
|
||||
case io.EOF:
|
||||
default:
|
||||
fmt.Println(err)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// this represents the request for the printer to send the count
|
||||
close(lines)
|
||||
// wait for the count from the printer, then print it, then exit
|
||||
fmt.Println("Number of lines:", <-count)
|
||||
}
|
||||
|
||||
func printer(in <-chan string, count chan<- int) {
|
||||
c := 0
|
||||
// loop as long as in channel stays open
|
||||
for s := range in {
|
||||
fmt.Println(s)
|
||||
c++
|
||||
}
|
||||
// make count available on count channel, then return (terminate goroutine)
|
||||
count <- c
|
||||
c := 0
|
||||
// loop as long as in channel stays open
|
||||
for s := range in {
|
||||
fmt.Print(s)
|
||||
c++
|
||||
}
|
||||
// make count available on count channel, then return (terminate goroutine)
|
||||
count <- c
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue