Suppose I’m parsing some kind of input with the following three methods:
func parseHeader ([]byte) []byte
func parseBody ([]byte) []byte
func parseFooter ([]byte) []byte
They all parse a certain part of the same input and return it as []byte, so they can be used like this:
i := []byte( /* the input */ )
b := new(bytes.Buffer)
b.Write(parseHeader(i))
b.Write(parseBody(i))
b.Write(parseFooter(i))
Now I’d like to make these 3 processes parallel by using channels. My idea was passing a channel to these functions for them to write to, but how can I make sure they will write in the correct order to the channel? (i.e. that the body is written to the channel after the header and the footer after the body)
Essentially you can’t, at least not without adding an additional layer of messages to do extra hand-shaking. What would be better to do is to use three separate channels and read from them in the order you want to receive them, that way you don’t need to worry about the write-order of the sending processes.
Here’s a minimal example: