我如何等到接收器通道完成它在 golang 中的执行?

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


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


Smart猫小萌
浏览 142回答 2
2回答

蓝山帝景

您可以编写 goroutine 以便它们相互等待。例如,这是一个位于生产者和消费者之间的中级传输器函数,并迫使他们缓慢前进:func middle(in, out chan int, inAck, outAck chan struct{}) {&nbsp; &nbsp; defer close(out)&nbsp; &nbsp; for value := range in {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("middle got", value)&nbsp; &nbsp; &nbsp; &nbsp; out <- value // send&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("middle now waiting for ack from final")&nbsp; &nbsp; &nbsp; &nbsp; <-outAck&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // wait for our consumer&nbsp; &nbsp; &nbsp; &nbsp; inAck <- struct{}{} // allow our producer to continue&nbsp; &nbsp; }}但总而言之,这是愚蠢的。强制生产者等到消费者完成并使用通道是没有意义的,因为如果我们想让生产者等待,我们只需编写:for ... {&nbsp; &nbsp; produced_value = producerStep()&nbsp; &nbsp; final(middle(produced_value))}whereproducerStep()产生下一个值,完全省去通道。

德玛西亚99

代码按预期工作。runLoop()但是你可以做一件事,在函数的两个连续步骤之间放置一定的间隔。但是不建议设置固定的时间间隔,您需要编写一些代码来确保完成这些工作。只是展示这个例子,向你展示这里发生了什么。func runLoop(second chan int) {&nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("writing i", i)&nbsp; &nbsp; &nbsp; &nbsp; second <- i&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(100 * time.Millisecond) // <-- here&nbsp; &nbsp; }}这里发生了什么?只需给予足够的时间来完成在单独的 goroutine 中运行的作业。输出:writing i 0seconds stats 0base stats 0writing i 1seconds stats 1base stats 1writing i 2seconds stats 2base stats 2writing i 3seconds stats 3base stats 3writing i 4seconds stats 4base stats 4
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go