Synchronous concurrency: Difference between revisions
Content added Content deleted
(Better example) |
(→{{header|Go}}: As documented, bufio.ReadString is preferred over bufio.ReadLine, this also removes the issue with long lines) |
||
Line 963: | Line 963: | ||
import ( |
import ( |
||
⚫ | |||
"fmt" |
|||
⚫ | |||
"io" |
|||
"os" |
|||
) |
) |
||
// main, one of two goroutines used, will function as the "reading unit" |
// main, one of two goroutines used, will function as the "reading unit" |
||
func main() { |
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) |
|||
// 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: |
|||
switch { |
|||
lines <- line |
|||
⚫ | |||
continue |
|||
case err != nil: |
|||
⚫ | |||
fmt.Println(err) |
|||
⚫ | |||
case prefix: |
|||
fmt.Println(err) |
|||
} |
|||
⚫ | |||
break |
|||
lines <- string(line) |
|||
} |
|||
continue |
|||
} |
|||
// this represents the request for the printer to send the count |
|||
break |
|||
⚫ | |||
} |
|||
// wait for the count from the printer, then print it, then exit |
|||
⚫ | |||
⚫ | |||
// wait for the count from the printer, then print it, then exit |
|||
⚫ | |||
} |
} |
||
func printer(in <-chan string, count chan<- int) { |
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 |
|||
}</lang> |
}</lang> |
||