synchronization - 同步 channel ?

标签 synchronization go channel goroutine

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

func parseHeader ([]byte) []byte
func parseBody   ([]byte) []byte
func parseFooter ([]byte) []byte

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

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

b.Write(parseHeader(i))
b.Write(parseBody(i))
b.Write(parseFooter(i))

现在我想通过使用 channel 使这 3 个进程并行。我的想法是向这些函数传递一个 channel 供它们写入,但是我如何确保它们以正确的顺序写入 channel ?(即正文写入 channel < em>在页眉和页脚之后正文)

最佳答案

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

这是一个最小的例子:

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)
}

关于synchronization - 同步 channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8873320/

相关文章:

java - 如何将多台机器的PATCH http请求同步到单台机器

linux - 网络文件系统挂载,本地回退?

go - golang中的接口(interface)和整数比较

go - 为什么在这个函数中使用 channel ?

smtp - System.Net.Mail.SmtpException : Service not available,关闭传输 channel 。服务器响应为: 4. 4.2

mongodb - 使用 meteor、cordova 在 sqlite 和 mongo 之间同步数据

go - 可以将 protobuf 编码消息发送到已分配的字节数组而无需复制吗?

javascript - 浏览器收到 Websocket 输出,提示 "Invalid UTF-8 sequence in header value "

go - 一个关于 Go Channel 的死锁及其原因的简单示例

Android SyncAdapter 回调