同步频道?

thw*_*hwd 1 synchronization channel go goroutine

假设我正在使用以下三种方法解析某种输入:

func parseHeader ([]byte) []byte
func parseBody   ([]byte) []byte
func parseFooter ([]byte) []byte
Run Code Online (Sandbox Code Playgroud)

它们都解析相同输入的某个部分并将其返回[]byte,因此它们可以像这样使用:

i := []byte( /* the input */ )
b := new(bytes.Buffer)

b.Write(parseHeader(i))
b.Write(parseBody(i))
b.Write(parseFooter(i))
Run Code Online (Sandbox Code Playgroud)

现在我想通过使用渠道使这三个过程并行.我的想法是将一个频道传递给这些函数供他们写入,但我怎样才能确保他们以正确的顺序写入频道呢?(即主体在标题和页脚后面写入通道)

sni*_*im2 5

基本上你不能,至少没有添加额外的消息层来做额外的握手.更好的做法是使用三个独立的通道,并按照您希望接收它们的顺序从中读取,这样您就不必担心发送进程的写入顺序.

这是一个最小的例子:

package main

import "fmt"

func sendme(num int, ch chan int) {
        ch <- num // send integer 'num' down chan ch
}

func main() {
        // Create three new channels
        one := make(chan int)
        two := make(chan int)
        three := make(chan int)

        // Start each parallel invocation of "sendme" as a go routine, in any order
        go sendme(3, three)
        go sendme(1, one)
        go sendme(2, two)

        // Read from each channel in the order we wish to process the
        // data
        fmt.Println(<- one, <- two, <- three)
}
Run Code Online (Sandbox Code Playgroud)