假设我正在使用以下三种方法解析某种输入:
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/