Synchronous concurrency: Difference between revisions

Content added Content deleted
(Added coroutine-version)
Line 578: Line 578:


reader printer @"c:\temp\input.txt"
reader printer @"c:\temp\input.txt"
</lang>

=={{header|Go}}==

<lang go>
package main

import (
"fmt"
"bufio"
"os"
)

func reader(file string, out chan string, count chan int, finish chan bool) {
f, _ := os.Open(file, os.O_RDONLY, 0) // ignore errors
defer f.Close()
rd := bufio.NewReader(f)
for s, err := rd.ReadString('\n'); err != os.EOF; s, err = rd.ReadString('\n') {
out <- s
}
close(out)
fmt.Println("Number of lines:", <-count)
finish <- true
}

func printer(in chan string, count chan int) {
c := 0
for s := range in {
fmt.Print(s)
c++
}
count <- c
}


func main() {
lines := make(chan string)
count := make(chan int)
finish := make(chan bool)
go reader("input.txt", lines, count, finish)
go printer(lines, count)
<-finish
}
</lang>
</lang>