gpt4 book ai didi

multithreading - 在 Go 中关闭自馈 channel

转载 作者:数据小太阳 更新时间:2023-10-29 03:22:18 26 4
gpt4 key购买 nike

我正在尝试使用 Go 中的并发和 channel 。我面临的问题主要是并发的想法,所以我不认为以下逻辑是错误的或者应该改变。

我有一个缓冲区大小为“N”的缓冲 channel ,它还代表将要创建的 goroutine 的数量。所有例程都从一个 channel 读取并写入另一个 channel ,主 goroutine 将打印来自最终 channel 的值。

1 个输入 channel --- N 个 goroutines 查找并添加到输入和输出 --- 1 个输出 channel

问题是我总是遇到死锁,因为我不知道如何关闭一个正在 self 馈送的 channel ,也不知道它什么时候会停止,所以我也无法关闭输出 channel 。

代码如下:

package main

const count = 3
const finalNumber = 100

// There will be N routines running and reading from the one read channel
// The finalNumber is not known, in this examples is 100, but in the main problem will keep self feeding until the operation gives a wrong output
// readingRoutine will feed read channel and the print channel
func readingRoutine(read, print chan int) {
for i := range read {
print <- i
if i < finalNumber && i+count < finalNumber {
read <- i + count
}
}
}

// This is the main routine that will be printing the values from the print channel
func printingRoutine(print chan int) {
for i := range print {
println(i)
}
}

func main() {
read := make(chan int, count)
print := make(chan int, count)

// Feed count numbers into the buffered channel
for i := 0; i < count; i++ {
read <- i
}

// count go routines will be processing the read channel
for i := 0; i < count; i++ {
go readingRoutine(read, print)
}
printingRoutine(print)
}

在此示例中,它应打印从 0 到 100 的所有数字并完成。谢谢

最佳答案

您可以使用 sync.WaitGroup 来等待事情完成,例如 wg := &sync.WaitGroup{}

当您尝试打印 finalNumber 次时,您应该调用 wg.Add(finalNumber) 然后在 print() 中,每次完成打印后,调用 wg.Done()

生成另一个 goroutine 等待 wg.Wait() 然后关闭 read channel 和 print channel 。

func printingRoutine(print chan int,wg *sync.WaitGroup) {
for i := range print {
println(i)
wg.Done()
}
}

func main() {
read := make(chan int, count)
print := make(chan int, count)
wg := &sync.WaitGroup{}
wg.Add(finalNumber)

// Feed count numbers into the buffered channel
for i := 0; i < count; i++ {
read <- i
}

// count go routines will be processing the read channel
for i := 0; i < count; i++ {
go readingRoutine(read, print)
}
go func() {
wg.Wait()
close(read)
close(print)
}()
printingRoutine(print,wg)
}

Playground :https://play.golang.org/p/BMSfz03egx0

关于multithreading - 在 Go 中关闭自馈 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51715210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com