2016 Update
This commit is contained in:
parent
948b86eafa
commit
dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions
|
|
@ -1,54 +1,32 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"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)
|
||||
lines := make(chan string)
|
||||
count := make(chan int)
|
||||
go func() {
|
||||
c := 0
|
||||
for l := range lines {
|
||||
fmt.Println(l)
|
||||
c++
|
||||
}
|
||||
count <- c
|
||||
}()
|
||||
|
||||
// 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 {
|
||||
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.Print(s)
|
||||
c++
|
||||
}
|
||||
// make count available on count channel, then return (terminate goroutine)
|
||||
count <- c
|
||||
f, err := os.Open("input.txt")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for s := bufio.NewScanner(f); s.Scan(); {
|
||||
lines <- s.Text()
|
||||
}
|
||||
f.Close()
|
||||
close(lines)
|
||||
fmt.Println("Number of lines:", <-count)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue