go - 我如何等待接收器 channel 完成它在golang中的执行?

标签 go goroutine

我有这个示例代码,我正在面对这个同步问题,任何人都可以帮助我如何实现这一目标。

package main

import "fmt"

func main() {

baseChan := make(chan int)
go func(bCh chan int){
for {
select{
    case stats, _ := <- bCh:
    fmt.Println("base stats", stats)
}}
}(baseChan)

second := make(chan int)
go func (sCh chan int) {
fmt.Println("second channel")
for {
select {
case stats, _ := <- sCh:
    fmt.Println("seconds stats", stats)
    baseChan <- stats
}
}
}(second)
runLoop(second)
}

func runLoop(second chan int) {
 for i := 0; i < 5; i++ {
fmt.Println("writing i", i)
    second <- i
}
}

实际输出:
writing i 0
second channel
seconds stats 0

base stats 0
writing i 1
writing i 2

seconds stats 1
seconds stats 2

我希望输出是这样的,
writing i 0
seconds stats 0
base stats 0

writing i 1
seconds stats 1
base stats 1

writing i 2
seconds stats 2
base stats 2

最佳答案

您可以编写goroutine,以便它们彼此等待。例如,这是一个位于生产者和消费者之间的中级运输者功能,它迫使他们沿着以下方向行走:

func middle(in, out chan int, inAck, outAck chan struct{}) {
    defer close(out)
    for value := range in {
        fmt.Println("middle got", value)
        out <- value // send
        fmt.Println("middle now waiting for ack from final")
        <-outAck            // wait for our consumer
        inAck <- struct{}{} // allow our producer to continue
    }
}

简而言之,这是愚蠢的。强制生产者等待直到消费者完成使用 channel 是没有道理的,因为如果我们要让生产者等待,我们只需编写:

for ... {
    produced_value = producerStep()
    final(middle(produced_value))
}

其中producerStep()产生下一个值,而完全不使用 channel 。

仍然是here is the complete stepping program on the Go playground

关于go - 我如何等待接收器 channel 完成它在golang中的执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61969749/

相关文章:

html - golang Beego中如何解析表单数组

go - 您既不在模块中,也不在 GOPATH 中

go - 如何知道 goroutine 是否还存在?

go - 为什么 channel 没有成为结构的成员

go - 不能将 type chan []string) 用作 type []chan string?

amazon-web-services - 带有 via amazonses.com 警告的 AWS SES SendRawEmail

go - 如何导入HTML类型?

go - 如何从 Go 库中获取对象构建信息?

go - 并发快速排序

Goroutine 从未在 Linux 上执行但在 Windows 上正常工作