Suppose that I have the following code to read lines and multiple each line by 2 and print each line out one by one.
I'd like to use N workers. Each worker takes M lines each time and processes them. More importantly, I'd like the output to be printed in the same order as the input. But the example here does not guarantee the output is printed in the same order as the input.
https://gobyexample.com/worker-pools
The following URL also shows some examples. But I don't think they fit my requirement. The problem is that the input can be arbitrarily long. There is no way to hold everything in memory before they are printed. There must be a way to get some output from the workers can determine if the output of a worker is ready to be printed and then it is print. It sounds like there should be a master goroutine to do this. But I am not sure how to implement it most efficiently, as this master gorountine can easily be a bottleneck when N is big.
How to collect values from N goroutines executed in a specific order?
Could anybody show an example program that results from the workers in order and prints the results as early as they can be printed?
$ cat main.go
#!/usr/bin/env gorun
// vim: set noexpandtab tabstop=2:
package main
import (
"bufio"
"fmt"
"strconv"
"io"
"os"
"log"
)
func main() {
stdin := bufio.NewReader(os.Stdin)
for {
line, err := stdin.ReadString('\n')
if err == io.EOF {
if len(line) != 0 {
i, _ := strconv.Atoi(line)
fmt.Println(i*2)
}
break
} else if err != nil {
log.Fatal(err)
}
i, _ := strconv.Atoi(line[:(len(line)-1)])
fmt.Println(i*2)
}
}